函数重载(overloaded function)和函数模板(function template)的小问题。
Posted on 2005-01-06 18:13 Panic 阅读(1208) 评论(1) 编辑 收藏问题其实很简单:
下面是一段正确的代码,模板 f(int a) 和f(float a)被作为f的不同重载版本。
template<int>
int f( int a)
{
cout << a << endl;
return a;
}
void f( float a)
{
cout << "float" << a << endl;
}
下面是一段有点问题的代码,在VC6.0下会有点小问题。
error C2556: 'void __cdecl f(int)' : overloaded function differs only by return type from 'int __cdecl f(int)'
template<int>
int f( int a)
{
cout << a << endl;
return a;
}
void f( int a)
{
cout << "void f:" << a << endl;
}
这段代码在其他编译器下有可能会被正确编译,但是事实上是不符合C++标准的。
C++标准规定( ISO/IEC 14882:1998(E) ):
Function declarations that differ only in the return type cannot be overloaded.
这里的两个f()其实正是这种情况。