SFINAE 和 sizeof 与 constexpr

SFINAE and sizeof vs constexpr

有时人们会这样写 (source):

template<typename T>
class is_class {
    typedef char yes[1];
    typedef char no [2];
    template<typename C> static yes& test(int C::*); // selected if C is a class type
    template<typename C> static no&  test(...);      // selected otherwise
  public:
    static bool const value = sizeof(test<T>(0)) == sizeof(yes);
};

有什么理由不将此类构造(基于sizeof)替换为基于constexpr的代码,例如以下代码?

template<typename T>
class is_class {
    template<typename C> static constexpr bool test(int C::*) { return true; } // selected if C is a class type
    template<typename C> static constexpr bool test(...) { return false; }     // selected otherwise
public:
    static bool constexpr value = test<T>(0);
};

我知道 constexpr 是该语言的一个相对较新的补充,但是除了必须使用旧标准(C++11 之前)之外,还有什么理由更喜欢第一个版本吗?

两种选择都可以。但它们之间的区别在于第一个不需要 C++11 而第二个需要。如果你至少可以自由使用 C++11——没有必要使用它们中的任何一个,标准库中已经有 std::is_class

因此,如果您在某个项目中看到这样的代码,那么这个项目应该在没有 C++11 支持的情况下编译,或者它是一些遗留的。