开发者

Overloading function on return type? (revisited)

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 fir开发者_如何学运维st case not have function overloading?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜