如何检查C++ 11中的类型是否相等?检查C++中的两种类型是否相等
std::uint32_t == unsigned; //#1
而另一片断
template<typename T> struct A{
string s = T==unsigned ? "unsigned" : "other";
}
如何检查C++ 11中的类型是否相等?检查C++中的两种类型是否相等
std::uint32_t == unsigned; //#1
而另一片断
template<typename T> struct A{
string s = T==unsigned ? "unsigned" : "other";
}
您可以使用从C++ 11日起std::is_same<T,U>::value
。
这里,T
,并且U
是类型和value
将true
如果他们是等价的,false
,如果他们不。
请注意,这是在编译时评估的。
为了好玩,试试这个:
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
并在返回类型中编码。
它看起来像你正在通过返回值重载'operator ==(tag_t,tag_t )'。这不是不允许的吗? –
Eric
@eric错字,第二个意思是'!='。我也在'>'和'=='之间缺少一个空格。 – Yakk