开发者

Overloading function on return type? (revisited)

开发者 https://www.devze.com 2023-02-24 09:12 出处:网络
Can someone tell me what different the compiler does in following two cases? #include <cstdio> using namespace std;

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

精彩评论

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

关注公众号