返回类型上重载函数? (重温)
有人能告诉我编译器在以下两种情况下有什么不同吗?
#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;
}
第一种情况没有函数重载吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当编译器遇到对模板函数的调用时,它使用模板自动生成一个函数,用作为实际模板参数传递的类型(在本例中为双精度)替换每个外观,然后调用它。这个过程是由编译器自动执行的,对程序员来说是不可见的。因此它还实现了数据抽象和隐藏。
编译器不会将模板视为普通函数或类。它们是根据需要编译的,这意味着模板函数的代码在需要时才编译。
第二个例子没有超载。你拼写错误转换。
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.