【发布时间】:2015-10-17 14:37:45
【问题描述】:
我正在寻找“is_comparable”类型特征,但找不到。
很容易构建一个检查类的operator== 是否已实现,但这不包括全局定义的运算符。
是不是不可能实现is_comparable typetait?
【问题讨论】:
标签: c++11 typetraits
我正在寻找“is_comparable”类型特征,但找不到。
很容易构建一个检查类的operator== 是否已实现,但这不包括全局定义的运算符。
是不是不可能实现is_comparable typetait?
【问题讨论】:
标签: c++11 typetraits
我认为你的意思是,对于两种类型 L 和 R 和
这些类型的对象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{};
这应用了一个流行的 SFINAE 模式来定义特征 回复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,"");
如果您希望特征要求相等是对称的并且不等式 也存在并且是对称的,你可以看看如何自己阐述它。
【讨论】:
Pair2 是一个断路器,是的。 sfinae 为时已晚。如果有人成功实现了 [EqualityComparable 概念] (en.cppreference.com/w/cpp/concept/EqualityComparable),他们一定已经破解了这个,但显然我没有。