2014-01-14 56 views
14

如果類型完全定義,是否可以使用SFINAE進行檢查?使用SFINAE來檢查類型是否完整

E.g.

template <class T> struct hash; 
template <>  struct hash<int> {}; 

// is_defined_hash_type definition... 

enum Enum { A, B, C, D }; 

static_assert ( is_defined_hash_type<int> ::value, "hash<int> should be defined"); 
static_assert (! is_defined_hash_type<Enum>::value, "hash<Enum> should not be defined"); 

該解決方案不應該修改哈希結構

回答

11

,您可根據is_complete型特徵,使用的事實,這是形成不良的評價sizeof(T)一個不完整的類型T

template <typename T> 
struct is_complete_helper { 
    template <typename U> 
    static auto test(U*) -> std::integral_constant<bool, sizeof(U) == sizeof(U)>; 
    static auto test(...) -> std::false_type; 
    using type = decltype(test((T*)0)); 
}; 

template <typename T> 
struct is_complete : is_complete_helper<T>::type {}; 

,並用它通過確定檢查is_defined_hash_type<T>如果hash<T>完成。 (Live at Coliru

正如丹尼爾在他的回答中所說,這種事情的效用是有限的。該特徵實際上並不測試該類型是否在您查詢的代碼中的位置完成,它測試該特徵是否在該特徵首次針對給定類型實例化的程序中的位置完成。

4

這是不可能的。原因是你必須定義is_defined_hash_type<T>但是隻能有一個的定義。但是如果您稍後定義了Tis_defined_hash_type<T>的定義會產生不同的結果,因此定義不同,這是不允許的。這違反了ODR(一個定義規則)。

+0

接受答案怎麼樣? – Orient

+0

@Oient正如凱西在他的回答中所說的那樣,這個特質在設計上相當破碎。這就是我在我的回答中解釋的 - 你的程序是非法的,即使它看起來有效,它也可能以微妙和不可預知的方式改變它的含義。 –

+0

我認爲這不構成問題,如果實例化對於TU來說是本地的並且沒有外部聯繫(簡單地排列)。但是這當然需要記住。此外,這可以通過添加標籤類型來緩解:'is_defined_hash_type ' – sehe

0

我想出了迄今以下,這需要至少有一個共同的名字typedefhash所有的專業化最佳:

template <class T> struct hash; 
template <>  struct hash<int> { 
    typedef int value_type; 
    }; 

template<class T> 
constexpr bool is_defined_hash_type(typename hash<T>::value_type) { 
    return true; 
} 

template<class T> 
constexpr bool is_defined_hash_type(T) { 
    return false; 
} 

int main() 
{ 
    static_assert ( is_defined_hash_type<int>(0), "hash<int> should be defined"); 
    static_assert (! is_defined_hash_type< double>(0), "hash<Enum> should not be defined"); 
    return 0; 
} 

的語法是很醜陋,由於添加參數(需要觸發SFINAE)。如果你認爲這可能是一條路,我會盡力進一步清理它。

聲明:我絕不是C++ 11專家,所以我可能錯過了一些使用新功能的要點。在這種情況下,我們會盡力解決答案。

+0

鏈接到[Coliru](http://coliru.stacked-crooked.com/a/e99682127caf1e5f) – Massimiliano

相關問題