why normal function can make a type cast while template function can't?

If I give two parameters the called function require but not that type, the compiler can make a type cast like below.

1
2
3
4
5
6
7
8
//function call
hello(1, 1.0);
//function definition
void hello(int a, int b)
{
cout << a << b << endl;
}


But with template functions, this doesn't work.
1
2
3
4
5
6
7
8
//function call
hello(1, 1.0);
//function definition
template <typename T>
void hello(T a, T b)
{
cout << a << b << endl;
}


Why normal function can which i wonder, in the condition that i didn't give a function overloading.
Last edited on
Because you must write your template like this:
1
2
3
4
5
6
//function definition
template <typename T>
void hello(T a, T b)
{
cout << a << b << endl;
}


And you must call it like this:

hello<int>(1, 1.0);
Last edited on
uh, I give the wrong code.
I mean when code like what you gave.
1
2
3
4
5
6
7
8
//function call
hello(1, 1.0);
//function definition
template <typename T>
void hello(T a, T b)
{
cout << a << b << endl;
}
Here is the explanation:

If you call
hello(1, 1.0);

and hello is a template, the compiler must determine what type to be used, right ? So it checks what are the types of the arguments, and find int and double. Since both types would valid for this template function, it doesn't have any way to choose which type to use. That's why you must help the compiler by telling which type it should use:
hello<int>(1,1.0);

Previously you didn't have this fact, because the compiler knew only the hello function that use int, and that's it. It didn't know any hello with double as argument.

Hope this helps
thanks a lot, now i see that :)
Topic archived. No new replies allowed.