尝试编译SFINAE检查中使用的方法体时发生编译错误

Compilation error when trying to compile body of a method used in SFINAE checks

本文关键字:编译 方法 错误 SFINAE 检查      更新时间:2023-10-16

我有一个众所周知的类示例,它可以检测类型是否为类。

#include <cstdio>
#include <type_traits>
template <typename T>                                        
class ClassDetector {
private:
typedef char One;
typedef struct { char a[2]; } Two;
template <typename C> static One test(int C::*) {
compilation error;
}
template <typename C> static Two test(...);
public:
enum { Yes = sizeof(ClassDetector<T>::test<T>(0)) == 1 };
enum { No = !Yes };
};
int main() {
printf("%dn", ClassDetector<int>::Yes);
return 0;
}

代码不在GCCClang上编译,因为"编译错误"在任何地方都没有定义,编译器也不知道它是什么。但它在Visual Studio下工作。这表明Visual Studio完全跳过了第一个test方法的主体,甚至不检查其中的任何内容。

所以,问题是:在这种情况下,谁是对的?GCC/Clang还是VS?是否应该检查该方法的编译错误,或者这不是必要的,也不是标准强制执行的?

您很可能是在VS中使用允许模式构建的,该模式禁用了两阶段查找(最近已经实现(。通过指定/permissive-参数禁用许可模式也会导致VS中的编译失败。