samedi 18 juillet 2020

SFINAE and sizeof vs constexpr

Sometimes people write something like the following (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);
};

Is there some reason not to replace such constructs (sizeof-based) with constexpr-based code, such as the following?

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

I know constexpr is a relatively new addition to the language, but is there any reason to prefer the first version other than having to use an old standard (pre-C++11)?

Aucun commentaire:

Enregistrer un commentaire