返回类型的重载功能?(重新)

Vin*_*ink 2 c++ compiler-construction templates

有人能告诉我两种情况下编译器的不同之处吗?

   #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;
    } 
Run Code Online (Sandbox Code Playgroud)

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;
} 
Run Code Online (Sandbox Code Playgroud)

第一种情况是否没有函数重载?

小智 7

当编译器遇到对模板函数的这个调用时,它使用模板自动生成一个函数,用作为实际模板参数传递的类型替换每个外观(在本例中为double),然后调用它.此过程由编译器自动执行,对程序员不可见.因此,它还实现了数据抽象和隐藏.

编译器不会将模板视为普通函数或类.它们是根据需求编译的,这意味着模板函数的代码在需要之前不会被编译.

第二个例子不是超载.你拼错了转换.