2016-09-23 227 views

回答

4

您可以使用從C++ 11日起std::is_same<T,U>::value

這裏,T,並且U是類型和valuetrue如果他們是等價的,false,如果他們不。

請注意,這是在編譯時評估的。

http://en.cppreference.com/w/cpp/types/is_same

2

爲了好玩,試試這個:

template<class T> 
struct tag_t { using type=T; constexpr tag_t() {}; }; 
template<class T> 
constexpr tag_t<T> tag{}; 

template<class T, class U> 
constexpr std::is_same<T, U> operator==(tag_t<T>, tag_t<U>) { return {}; } 
template<class T, class U> 
constexpr std::integral_constant<bool, !(tag<T> == tag<U>)> operator!=(tag_t<T>, tag_t<U>) { return {}; } 

現在你可以鍵入tag<T> == tag<unsigned>。結果是constexpr並在返回類型中編碼。

live example

+0

它看起來像你正在通過返回值重載'operator ==(tag_t ,tag_t )'。這不是不允許的嗎? – Eric

+0

@eric錯字,第二個意思是'!='。我也在'>'和'=='之間缺少一個空格。 – Yakk

相關問題