implicit specification of template

In C++ programming language book, it says:
1
2
3
4
5
template<class T, class U> 
T implicit_cast(U u) { return u; }
void g(int i) {
implicit_cast(i); // error: can’t deduce T 
implicit_cast<double>(i); // T is double; U is int 


I still cannot figure out why error in implicit_cast(i); i is an integer, and return u is also an integer. So does the compiler deduct that T is an integer type? Thanks:)

implicit_cast(i); // error: can’t deduce T

Here, the compiler can deduce 'U', but not 'T'.
'U' is known because it knows that whatever is passed to the function is of type U. Since 'i' is being passed, and since 'i' is an int, it then knows that U=int

However it's impossible to know what 'T' is here, because it cannot be determined by the function call. Which is why you get the compiler error.

implicit_cast<double>(i); // T is double; U is int

Here, T=double
and U=int

T=double is known because you are explicitly setting it with the "<double>" template param
U=int is known for the same reason it was known above. 'i' is being passed as the paramter, therefore U=whatever type 'i' is, and 'i' is an int.
Last edited on
OK, got it. Thanks for you timely help. It seems that the compiler is not smart enough:)
PICNIC. Machines are obedient.
¿Are you "smart" enough to do it?
haha, I will try:)
Topic archived. No new replies allowed.