如何在C ++ 11中static_assert
模板类型是EqualityComparable概念?
答案 0 :(得分:18)
您可以使用以下类型特征:
#include <type_traits>
template<typename T, typename = void>
struct is_equality_comparable : std::false_type
{ };
template<typename T>
struct is_equality_comparable<T,
typename std::enable_if<
true,
decltype(std::declval<T&>() == std::declval<T&>(), (void)0)
>::type
> : std::true_type
{
};
你会用这种方式测试:
struct X { };
struct Y { };
bool operator == (X const&, X const&) { return true; }
int main()
{
static_assert(is_equality_comparable<int>::value, "!"); // Does not fire
static_assert(is_equality_comparable<X>::value, "!"); // Does not fire
static_assert(is_equality_comparable<Y>::value, "!"); // Fires!
}
这是live example。