2016-09-23 106 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

相关问题