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?
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
© 2022 - 2024 — McMap. All rights reserved.
f(b, a)
should convertdouble
toint
orint
todouble
or fail to compile. It doesn't explain whether he wants this treatment also forshort a; f(a, b)
. Neither which are the supported types offun
. 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