3

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?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
maple
  • 1,828
  • 2
  • 19
  • 28
  • Why was the question downvoted? It is a legitimate question. – SergeyA Apr 15 '16 at 13:57
  • @SergeyA I did not downvote (reading it only now), but the question is a bit ambiguous and doesn't explain rationale at all. It doesn't explain whether `f(b, a)` should convert `double` to `int` or `int` to `double` or fail to compile. It doesn't explain whether he wants this treatment also for `short a; f(a, b)`. Neither which are the supported types of `fun`. I would have answered "*yes, use fun(double a, T b)*", but the question has no information on whether that's useless or not. Not enough reason to downvote for me. I will just move on and won't be bothered. – Johannes Schaub - litb Apr 15 '16 at 15:32

3 Answers3

8

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); 
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
0

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);
Barry
  • 286,269
  • 29
  • 621
  • 977
0

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
shrike
  • 4,449
  • 2
  • 22
  • 38