C ++ 11静态断言的相等类型?

时间:2013-05-06 13:01:36

标签: c++ templates c++11 equality static-assert

如何在C ++ 11中static_assert模板类型是EqualityComparable概念?

1 个答案:

答案 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