在c++中测试数据是否属于某种数据类型

Test whether the data belong to certain data type in C++?

本文关键字:数据类型 属于 是否 c++ 测试数据      更新时间:2023-10-16
datatype *x;//where datatype is a class defined earlier;
//...
if (isDataType(x[0]))//test whether x[0] belong to datatype defined.
//do something

有没有c++函数可以做上面的工作?

使用std::is_same:

#include <type_traits>
if ( std::is_same<datatype, decltype(x[0])>::value ) {
}
bool isDataType(const datatype&) { return true; }
template<typename T> bool isDataType(const T&) { return false; }