Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 static assert for equality comparable type?

How to static_assert a template type is EqualityComparable concept in C++11?

like image 652
eonil Avatar asked May 06 '13 13:05

eonil


1 Answers

You could use the following type trait:

#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
{
};

Which you would test this way:

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!
}

Here is a live example.

like image 164
Andy Prowl Avatar answered Oct 11 '22 22:10

Andy Prowl