简体   繁体   English

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

[英]Implicit type conversion in c++ template

I have a function template: 我有一个功能模板:

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

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

can a be converted to double automatically? 可以自动转换为双倍?

can a be converted to double automatically? 可以自动转换为双倍?

No, because it's ambiguous between fun<int> and fun<double> , when deducing the type of T in template argument deduction . 不,因为在fun<int>fun<double> ,当在模板参数推断中推导出T的类型时,它是不明确的。

You could specify the template argument explicitly, to make a implicitly converted to double : 你可以显式地指定模板参数,使a隐式转换为double

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

or add an explicit conversion, to make the template argument deduction unambiguous: 或添加显式转换,以使模板参数推断明确:

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

No it can't. 不,它不能。 There are no conversions done during the template deduction process. 在模板扣除过程中没有完成转换。 In this case, we deduce T independently from a and b , getting int for a and double for b - since we deduced T to be two different types, that is a deduction failure. 在这种情况下,我们从ab独立地推导出T ,得到ab int和为b得到的double - 因为我们推导出T是两种不同的类型,即推导失败。

If you want to do conversions, the simplest thing would either be to explicitly do it yourself: 如果你想做转换,最简单的事情就是自己明确地做:

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

Or to explicitly provide the template parameter to f so that no deduction happens: 或者明确地将模板参数提供给f以便不进行演绎:

f<double>(a, b);

If your intention is that parameter a be converted to type of parameter b , then the following template can be used instead of yours: 如果您的意图是将参数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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM