implicit specification of template

Mar 26, 2012 at 3:08am
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:)

Mar 26, 2012 at 3:13am
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 Mar 26, 2012 at 3:14am
Mar 26, 2012 at 3:18am
OK, got it. Thanks for you timely help. It seems that the compiler is not smart enough:)
Mar 26, 2012 at 3:53am
PICNIC. Machines are obedient.
¿Are you "smart" enough to do it?
Mar 26, 2012 at 3:56am
haha, I will try:)
Topic archived. No new replies allowed.