假设我有一个简单的nullary模板函数模板化在一个参数上,有两个特化,一个用于unsigned long,一个用于size_t(内容不重要):
template<typename T> T f(void);
template<> unsigned long f<unsigned long>(void) { return 1; }
template<> size_t f<size_t>(void) { return 2; }
Run Code Online (Sandbox Code Playgroud)
我的理解是该类型的确切定义size_t是依赖于平台的,因此它可能相同或不相同unsigned long.在我目前的平台上(Cygwin g ++ 5.2.0在Windows 10上进行64位编译-std=gnu++1y)这两种类型看起来是等价的,所以上面的代码无法编译:
../test.cpp:51:19: error: redefinition of ‘T f() [with T = long unsigned int]’
template<> size_t f<size_t>(void) { return 2; }
^
../test.cpp:50:26: note: ‘T f() [with T = long unsigned int]’ previously declared here
template<> unsigned long f<unsigned long>(void) { return 1; } …Run Code Online (Sandbox Code Playgroud) c++ templates conditional-compilation template-meta-programming
考虑:
void f() {
return 5;
}
Run Code Online (Sandbox Code Playgroud)
以上会引起错误.但为什么不呢?:
template <typename = void> void f() {
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我正在用gcc-4.5.1编译.为什么使用模板会产生差异,以至于我不会因为非模板函数执行相同的非法返回语句而收到错误?我得到的唯一挫折是我无法调用函数(即f())而没有得到:
error: return-statement with a value, in function returning 'void'
但是,我能够为void函数模板定义return语句的原因是什么?
这是我的代码:
template <typename = void> void f() {
return 0;
}
// pass
int main() {
}
Run Code Online (Sandbox Code Playgroud)
尽管在返回void的函数中有一个非法的返回语句,上面的代码仍将通过.