c++检测数字类型
时间: 2023-08-03 08:16:56 浏览: 49
C++中可以使用`typeid`运算符或者类型模板来检测数据类型。
1. `typeid`运算符
`typeid`运算符可以返回一个`std::type_info`类型的对象,表示表达式的静态类型。可以使用`type_info`对象的`name()`函数获取类型名称。例如:
```c++
#include <iostream>
#include <typeinfo>
int main() {
int a = 1;
double b = 2.0;
std::cout << typeid(a).name() << std::endl; // 输出i
std::cout << typeid(b).name() << std::endl; // 输出d
return 0;
}
```
2. 类型模板
类型模板可以将不同类型的数据作为参数,返回相同类型的函数。可以使用模板函数来检测数据类型。例如:
```c++
#include <iostream>
#include <type_traits>
template <typename T>
void checkType(T t) {
if (std::is_integral<T>::value) {
std::cout << "t is an integer." << std::endl;
} else if (std::is_floating_point<T>::value) {
std::cout << "t is a floating point number." << std::endl;
} else {
std::cout << "t is neither an integer nor a floating point number." << std::endl;
}
}
int main() {
int a = 1;
double b = 2.0;
char c = 'c';
checkType(a); // 输出t is an integer.
checkType(b); // 输出t is a floating point number.
checkType(c); // 输出t is neither an integer nor a floating point number.
return 0;
}
```
运行结果为:
```
t is an integer.
t is a floating point number.
t is neither an integer nor a floating point number.
```