c ++模板中的隐式类型转换

时间:2016-04-15 13:50:55

标签: c++ templates

我有一个功能模板:

template<typename T>
void fun(T a, T b){
         .......
}

int a = 0;
double b = 1.2;
f(a, b);

可以自动转换为双倍吗?

3 个答案:

答案 0 :(得分:7)

  

可以自动转换为双倍吗?

不,因为在template argument deduction中推断fun<int>的类型时,fun<double>T之间的含糊不清。

您可以明确指定模板参数,以使a隐式转换为double

int a = 0;
double b = 1.2;
fun<double>(a, b); 

或添加显式转换,以使模板参数演绎明确:

int a = 0;
double b = 1.2;
fun(static_cast<double>(a), b); 

答案 1 :(得分:0)

不,它不能。在模板扣除过程中没有完成转换。在这种情况下,我们会从Ta独立推导bint获取adouble获取b - 因为我们推导T是两种不同的类型,这是演绎失败。

如果你想进行转换,最简单的事情就是自己明确地做:

f(static_cast<double>(a), b);

或者明确地将模板参数提供给f,以便不进行演绎:

f<double>(a, b);

答案 2 :(得分:0)

如果您的意图是将参数a转换为参数b的类型,则可以使用以下模板代替您的模板:

template<typename Ta, typename T>
void fun(Ta aTa, T b) {
    T& a = static_cast<T>(aTa);
    /* ... a and b have the same type T ... */
}

int a = 0;
double b = 1.2;
fun(a, b);    // works fine
相关问题