首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >寻找"is_comparable“类型

寻找"is_comparable“类型
EN

Stack Overflow用户
提问于 2015-10-17 14:37:45
回答 1查看 778关注 0票数 10

我在找一种"is_comparable“型,但找不到。

构建一个检查类的operator==是否实现的方法非常容易,但这不包括全局定义的操作符。

不可能实现is_comparable类型吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-10-18 10:11:00

我认为您的意思是,对于LR两种类型,以及这些类型的对象lhsrhs,如果lhs == rhs要编译,那么false就会产生true。在理论上,您理解lhs == rhs可能编译,尽管rhs == lhslhs != rhs没有编译。

在这种情况下,您可能会实现如下特性:

代码语言:javascript
复制
#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 question的答案中已经解释过了。

一些插图:

代码语言:javascript
复制
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,"");

如果你想要求平等是对称的,不平等也是存在的,并且是对称的,你可以看到如何自己来阐述它。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33187789

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档