寻找"is_comparable";类型特征 [英] Looking for "is_comparable" typetrait

查看:38
本文介绍了寻找"is_comparable";类型特征的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找"is_comparable"类型特征,但找不到任何特征.

I'm looking for an "is_comparable" typetrait but can't find any.

构建一个用于检查是否为类实现了 operator == 的代码非常容易,但这不包括全局定义的运算符.

It's very easy to build one that checks if an operator== for a class was implemented, but this excludes global defined operators.

是否不可能实现is_comparable typetait?

Is it impossible to implement a is_comparable typetait?

推荐答案

我认为这是一个特征,对于两种类型的 L R 这些类型的对象 lhs rhs 如果满足以下条件,将产生 true lhs == rhs 将编译,否则 false .你感激从理论上讲,即使 rhs == lhs lhs!= rhs lhs == rhs 也可能会编译,没有.

I take it you mean a trait that, for two types L and R and objects lhs and rhs of those types respectively, will yield true if the lhs == rhs will compile and false otherwise. You appreciate that in theory lhs == rhs might compile even though rhs == lhs, or lhs != rhs, does not.

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

In that case you might implement the trait like:

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

这适用于流行的SFINAE模式以定义特征,对此进行了解释在这个问题的答案

This applies a popular SFINAE pattern for defining traits that is explained in the answer to this question

一些插图:

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,"");

如果您希望特征要求平等是对称的并且不平等也存在并且是对称的,您可以自己了解如何制作.

If you want the trait to require that equality is symmetric and that inequality also exists and is symmetric you can see how to elaborate it yourself.

这篇关于寻找"is_comparable";类型特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆