寻找"is_comparable"typetrait

Gen*_*ene 6 type-traits c++11

我正在寻找一个"is_comparable"typetrait但找不到任何东西.

构建一个检查operator==类是否已实现的内容非常容易,但这会排除全局定义的运算符.

是否无法实现is_comparable类型?

Mik*_*han 7

我认为你的意思是一个特征,对于两种类型LR对象lhs以及rhs这些类型分别,true如果lhs == rhs将编译则将产生,false否则。您知道理论上lhs == rhs可以编译,即使rhs == lhs, 或lhs != rhs, 不能编译。

在这种情况下,您可以实现如下特征:

#include <type_traits>

template<class ...> using void_t = void;

template<typename L, typename R, class = void>
struct is_comparable : std::false_type {};

template<typename L, typename R>
using comparability = decltype(std::declval<L>() == std::declval<R>());

template<typename L, typename R>
struct is_comparable<L,R,void_t<comparability<L,R>>> : std::true_type{};
Run Code Online (Sandbox Code Playgroud)

这应用了流行的 SFINAE 模式来定义特征,该模式在这个问题的答案中进行了解释

一些插图:

struct noncomparable{};

struct comparable_right
{
    bool operator==(comparable_right const & other) const {
        return true;
    }
};

struct any_comparable_right
{
    template<typename T>
    bool operator==(T && other) const {
        return false;
    }
};

bool operator==(noncomparable const & lhs, int i) {
    return true;
}

#include <string>

static_assert(is_comparable<comparable_right,comparable_right>::value,"");
static_assert(!is_comparable<noncomparable,noncomparable>::value,"");
static_assert(!is_comparable<noncomparable,any_comparable_right>::value,"");
static_assert(is_comparable<any_comparable_right,noncomparable>::value,"");
static_assert(is_comparable<noncomparable,int>::value,"");
static_assert(!is_comparable<int,noncomparable>::value,"");
static_assert(is_comparable<char *,std::string>::value,"");
static_assert(!is_comparable<char const *,char>::value,"");
static_assert(is_comparable<double,char>::value,"");
Run Code Online (Sandbox Code Playgroud)

如果您希望该特征要求平等是对称的,并且不平等也存在并且是对称的,您可以看看如何自己详细阐述。