2015-10-17 45 views
6

我正在尋找一個「is_comparable」typetrait,但找不到任何。尋找「is_comparable」typetrait

構建一個用於檢查某個類的operator==是否已實現的構建非常容易,但是這不包括全局定義的運算符。

是不可能實現is_comparable typetait?

回答

3

我想你的意思是一個特點,對於兩種類型的LR和 對象lhs分別那些類型的rhs,將產生true如果 的lhs == rhs編譯和false否則。您理解 理論上lhs == rhs可能會編譯即使rhs == lhslhs != 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,""); 

如果你想讓特質要求等式是對稱的,那個不等式 也存在,是對稱的,你可以看到如何自己闡述它。

+0

Thx爲您的答案,但它不起作用。嘗試使用gcc編譯此代碼時,即使您的static_assert失敗。問題似乎是「std :: declval ()== std :: declval ()」,它不會被評估。有趣的是,clang-3.8像我所期望的那樣拋出一個編譯異常。 – Gene

+0

@Gene奇怪,它爲我編譯[gcc 5.2 live](https://goo.gl/0Le5lw)和[clang 3.6 live](https://goo.gl/uLkdnm)。 也許你可以發佈你的失敗的編譯? –

+0

有趣......我用gcc 4.9.2也在抱怨static_assert。我的本地例子也稍微複雜一些。我在最後添加了一對定義,這使得叮噹3.6的生活也意外失敗:https://goo.gl/OKsuIU – Gene