maple
maple

Reputation: 1892

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?

Upvotes: 3

Views: 1070

Answers (3)

shrike
shrike

Reputation: 4511

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

Upvotes: 0

songyuanyao
songyuanyao

Reputation: 173024

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); 

Upvotes: 8

Barry
Barry

Reputation: 303870

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);

Upvotes: 0

Related Questions