Implicit type conversion in c++ template
Asked Answered
R

3

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?

Raisaraise answered 15/4, 2016 at 13:50 Comment(2)
Why was the question downvoted? It is a legitimate question.Telemark
@Telemark 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.Cleghorn
H
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); 
Hiramhirasuna answered 15/4, 2016 at 13:55 Comment(0)
C
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);
Crossrefer answered 15/4, 2016 at 13:56 Comment(0)
C
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
Concertante answered 15/4, 2016 at 16:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.