C++使用泛型判断变量类型

09. October 2020 笔记 0
#include <iostream>
using namespace std;

template <typename T>
string what_is_it(T x){
	if(typeid(x)==typeid(int)){
	return "an int";
	}else if(typeid(x)==typeid(bool)){
	return "an bool";
	}else if(typeid(x)==typeid(char)){
	return "an char";
	}else if(typeid(x)==typeid(float)){
	return "an float";
	}else if(typeid(x)==typeid(double)){
	return "an double";
	}else{
	return "undefined";
	}
}

int main()
{
	int a=10;
	bool b=true;
	char c='a';
	float d=3.14;
	double e=3.1415926;
	cout << what_is_it(a) << endl; 
	cout << what_is_it(b) << endl; 
	cout << what_is_it(c) << endl; 
	cout << what_is_it(d) << endl; 
	cout << what_is_it(e) << endl; 
   return 0;
}