提问者:小点点

SFINAE和sizeof vs constexpr


有时人们会写一些像下面这样的东西(出处):

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);
};

是不是有什么理由不用基于constexpr的代码替换这样的构造(sizeof的),例如下面的代码?

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是语言中的一个相对较新的添加,但是除了必须使用旧标准(Pre-C++11)之外,还有什么理由更喜欢第一个版本吗?


共1个答案

匿名用户

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

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