检查两个类型在c++中是否相等

Check if two types are equal in C++

本文关键字:c++ 是否 类型 两个 检查      更新时间:2023-10-16

如何检查c++ 11中的类型是否相等?

 std::uint32_t == unsigned;  //#1

和另一个片段

template<typename T> struct A{ 
  string s = T==unsigned ? "unsigned" : "other";
}

从c++ 11开始可以使用std::is_same<T,U>::value

这里,TU是类型,如果它们相等,则valuetrue,如果它们不相等,则为false

请注意,这是在编译时计算的。

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

为了好玩,试试这个:

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,并在返回类型中编码。

生活例子。

在c++ 17中,可以使用:

#include <type_traits>
if constexpr(std::is_same_v<T,U>) { /* do something*/ }