Reputation: 49
I saw this code in the internet:
template <class T, class S>
T f(T& a, T& b, S c) {
T t1, t2, t3;
if (a==b) return t1;
if (c>0) return t2;
return t3;
}
Followed by these calls:
f('c', 5, 5); // why this doesn't compile?
f(3, 4, 6.0); // why does this compile?
The first one doesn't compile, while the second does.. Why?
Upvotes: 0
Views: 69
Reputation: 320381
In C++ (as opposed to C) 'c'
is a char
.
Your code does not compile because template argument deduction for parameter T
fails - it is ambiguous. In f('c', 5, 5)
call the first function argument says it should be char
, the second says it should be int
. How did you expect the compiler to resolve this ambiguity?
If you want T == int
you can specify the first template argument explicitly
f<int>('c', 5, 5);
or you can use an explicit cast
f((int) 'c', 5, 5);
Of course, as it has already been noted, even if you get through the template argument deduction issues, you still won't be able to initialize non-constant lvalue references with rvalues. Both of your calls are invalid too, for this latter reason.
Upvotes: 4