【发布时间】:2017-02-01 12:33:39
【问题描述】:
如何在 C++11 中检查类型是否相等?
std::uint32_t == unsigned; //#1
还有一个sn-p
template<typename T> struct A{
string s = T==unsigned ? "unsigned" : "other";
}
【问题讨论】:
标签: c++ c++11 typetraits
如何在 C++11 中检查类型是否相等?
std::uint32_t == unsigned; //#1
还有一个sn-p
template<typename T> struct A{
string s = T==unsigned ? "unsigned" : "other";
}
【问题讨论】:
标签: c++ c++11 typetraits
您可以从 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<T>, tag_t<U> )。这不是不允许的吗?
!=。我还缺少> 和== 之间的空格。