Reputation: 1039
Can someone tell me what different the compiler does in following two cases?
#include <cstdio>
using namespace std;
template <typename TReturn, typename T>
TReturn convert(T x)
{
return x;
}
int main()
{
printf("Convert : %d %c\n", convert<int, double>(19.23), convert<char, double>(100));
return 0;
}
AND
int convert(double x)
{
return 100;
}
char convert(double x)
{
return 'x';
}
int main()
{
printf("Convert : %d %c\n", convert(19.23), convert(100)); // this doesn't compile
return 0;
}
Does the first case not have function overloading?
Upvotes: 2
Views: 137
Reputation:
When the compiler encounters this call to a template function, it uses the template to automatically generate a function replacing each appearance by the type passed as the actual template parameter (double in this case) and then calls it. This process is automatically performed by the compiler and is invisible to the programmer. Thus it also implements data abstraction and hiding.
The compiler does not treat templates as normal functions or classes. They are compiled on requirement, meaning that the code of a template function is not compiled until required.
Second exmaple is not overloading. You misspelled convert.
Upvotes: 7