问题:
在自定义的模版类中,根据实例化后的数据类型来进行不同的打印输出
// 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/