c++写段程序,在泛型函数内判断数据类型
时间: 2024-02-09 21:13:23 浏览: 20
你可以使用C++模板来实现泛型函数的数据类型判断。以下是一个示例:
```c++
#include <iostream>
template <typename T>
void check_type(T arg)
{
if (std::is_same<T, int>::value) {
std::cout << "The argument is an integer." << std::endl;
} else if (std::is_same<T, double>::value) {
std::cout << "The argument is a double." << std::endl;
} else if (std::is_same<T, char>::value) {
std::cout << "The argument is a character." << std::endl;
} else {
std::cout << "The argument is of an unknown type." << std::endl;
}
}
int main()
{
int a = 1;
double b = 1.0;
char c = 'a';
check_type(a);
check_type(b);
check_type(c);
return 0;
}
```
在上面的示例中,我们使用了C++标准库中的`std::is_same`函数来判断模板类型`T`是否与指定类型相同。如果相同,则打印相应的消息,否则打印未知类型的消息。您可以根据需要添加更多的类型判断条件。