如何在c++中检查变量的类型

How to check the type of a variable in c++

本文关键字:变量 类型 检查 c++      更新时间:2023-10-16

我需要一个函数来判断变量是否为Integral。返回布尔的函数

您可以将std::is_integral_v(或std::is _integral::value pre C++17(封装在两个辅助函数中,即:

template<typename T>
bool isIntegral(const T& value)
{
return std::is_integral_v<T>;
}
template<typename T>
bool isIntegral()
{
return std::is_integral_v<T>;
}

示例用法:

int i = 0;
std::cout << std::boolalpha;
std::cout << isIntegral(i) << std::endl;
std::cout << isIntegral<int>();

使用typeid在运行时查找类型。

int i = 3;
cout << "i's typeid().name: ";
cout << typeid(i).name() << endl;