【转载】C++ 模板种中的类型判断和针对不同类型定义不同的方法

【转载】C++ 模板类中的类型判断和针对不同类型定义不同的方法

转载自:http://blog.****.net/mykoma521/archive/2010/06/14/5670988.aspx

在C++中,使用template,有时候可能会需要得到当前所使用的类型.
本文中使用两种办法来。
TT类为使用模板的类,
TT.h
#ifndef _TT_H
#define _TT_H
#include "stdio.h"
template <class T>
class TT{
public:
    void printType();
    void printType(T);
};
方法1: 实现对不同类型定义不同的方法
template<>
void TT<int>::printType(){
    printf("int\n");
}
template<>
void TT<char>::printType(){
    printf("char\n");
}
template<class T>
void TT<T>::printType(){
    printf("other type\n");
}
方法1结束。
方法2:
template<class T>
void TT<T>::printType(T t){ //判断t是不是int类型的
    printf("%d\n",typeid(t).name() == typeid(1).name()); // 得到t的类型名称
}
方法2结束。
#endif
main.c
#include "TT.h"
int main(){
    TT<int> t1;
    TT<char> t2;
    TT<double> t3;
    t1.printType();
    t2.printType();
    t3.printType();
    int a = 1;
    char b = 'b';
    double c = 1.1;
    t1.printType(a);
    t2.printType(b);
    t3.printType(c);
    return 0;
}
最后的结果为:
int
char
other type
1
0
0

 

---------------EOF----------------