C++中template如何判断类型

在C++中,使用template,有时候可能会需要得到当前所使用的类型.

本文中使用两种办法来。

 

TT类为使用模板的类,

 

TT.h

#ifndef _TT_H

#define _TT_H

#include "stdio.h"

template

class TT{

public:

    void printType();

    void printType(T);

};

 方法1:

template<>

void TT::printType(){

    printf("int/n");

}

template<>

void TT::printType(){

    printf("char/n");

}

template

void TT::printType(){

    printf("other type/n");

}

 方法1结束。

方法2:

template

void TT::printType(T t){//判断t是不是int类型的

    printf("%d/n",typeid(t).name() == typeid(1).name());

}

方法2结束。

#endif

 

main.c

#include "TT.h"

int main(){

    TT t1;

    TT t2;

    TT 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

你可能感兴趣的:(C++中template如何判断类型)