简体   繁体   中英

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 .

You could specify the template argument explicitly, to make a implicitly converted to 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.

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<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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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