在C++中判断模版实例化后的数据类型

问题:

在自定义的模版类中,根据实例化后的数据类型来进行不同的打印输出

// class templates
#include <iostream>
#include <typeinfo.h>
using namespace std;

template <class T>
class mypair {
	T a, b;
	T * pTable;
	int TableLength;
public:
	mypair (T first, T second)
	{a=first; b=second;}
	mypair (void* pIn);
	mypair (void* pIn,int n);
	T getmax ();
	void printTable();
};

template <class T>
T mypair<T>::getmax ()
{
	T retval;
	retval = a>b? a : b;
	return retval;
}

template <class T>
mypair<T>::mypair (void* pIn)
{
	pTable = (T*)pIn;
}
template <class T>
mypair<T>::mypair (void* pIn, int n)
{
	pTable = (T*)pIn;
	TableLength = n;
}
template <class T>
void mypair<T>::printTable()
{
	//int tmp;
	//string mystring(&typeid(tmp).name);
	printf("%s \n",typeid(T).name());
	//const char*pchar = typeid(tmp).name();
	if (!strcmp(typeid(T).name(),"int"))
	{
		for (int i=0;i<TableLength;i++)
		{
			printf("%d \t",pTable[i]);
		}
		printf("\n");
	}
	else if (!strcmp(typeid(T).name(),"float"))
	{
		for (int i=0;i<TableLength;i++)
		{
			printf("%f \t",pTable[i]);
		}
		printf("\n");
	}
}
int main () {
	mypair <int> myobject (100, 75);

	cout << myobject.getmax()<<endl;


	int inDate [11] ={0,1,2,3,4,5,6,7,8,9,10};
	mypair<int> myobject2((void*)inDate,6);
	myobject2.printTable();

	float inDateFloat [11] ={0.0,1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9,10.0};
	mypair<float> myobject3((void*)inDateFloat,6);
	myobject3.printTable();
	return 0;
}

输出:

100
int
0       1       2       3       4       5
float
0.000000        1.100000        2.200000        3.300000        4.400000        5.500000
请按任意键继续. . .


头文件:#include <typeinfo>

http://www.cplusplus.com/reference/typeinfo/type_info/

http://en.cppreference.com/w/cpp/language/typeid

http://en.cppreference.com/w/cpp/types/type_info

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值