检查两个类型在c++中是否相等
Check if two types are equal in C++
如何检查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
这里,T
和U
是类型,如果它们相等,则value
为true
,如果它们不相等,则为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*/ }
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 检查输入是否不是整数或数字
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 此代码是否违反一个定义规则
- 是否需要删除包含对象的"pair"?
- 是否可以从int转换为enum类类型
- 无论条件是否为true,if总是在c++中执行
- 如何找到大小'x'数组是否完全填充,在C++?
- 检查值是否在集合p1和p2中,但不在p3中
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 检查 std::shared_ptr<> 的当前底层类型是否为 T
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- C/C++预处理器是否可以检测一些编译器选项
- 是否可以用"iostream"包装现有的TCP/OOpenSSL会话