Reputation: 435
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)?
Upvotes: 3
Views: 252
Reputation: 2324
Both options would work. But the difference between them is that the first one doesn't require C++11 while the second one does. And if you are free to use at least C++11 - there is no need to use any of them, there is already std::is_class in the standard library.
So if you see such code in some project then either this project is supposed to compile without C++11 support or it's some legacy.
Upvotes: 2