以下 C++ 代码可以为 GNU g++、LLVM 和我扔给它的所有其他 C++ 编译器正确编译和运行,Microsoft VC6 和 VC7 除外:
template<typename A, typename B> int HasVoidReturnType(A(*)(B)) { return 0; }
template<typename B> int HasVoidReturnType(void(*)(B)) { return 1; }
void f(double) {}
int foo() { return HasVoidReturnType(f); }
对于 VC6 和 VC7,编译失败并报错:
f.cpp(4) : error C2667: 'HasVoidReturnType' : none of 2 overloads have a best conversion
f.cpp(2): could be 'int HasVoidReturnType(void (__cdecl *)(B))'
f.cpp(1): or 'int HasVoidReturnType(A (__cdecl *)(B))'
while trying to match the argument list '(overloaded-function)'
f.cpp(4) : error C2668: 'HasVoidReturnType' : ambiguous call to overloaded function
f.cpp(2): could be 'int HasVoidReturnType(void (__cdecl *)(B))'
f.cpp(1): or 'int HasVoidReturnType(A (__cdecl *)(B))'
while trying to match the argument list '(overloaded-function)'
与其争论什么编译器是正确的优点,我如何使用 VC6 和 VC7 从模板函数中确定函数是否具有 void 返回类型?