首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

怎么知道Template传进来的参数的类型

2012-04-23 
如何知道Template传进来的参数的类型?假如有个函数template typename Tvoid add(T t){// 如何知道t的参

如何知道Template传进来的参数的类型?
假如有个函数
template <typename T>
void add(T t)
{
// 如何知道t的参数类型,int? float?
}

[解决办法]

C/C++ code
template<class T> struct Type{               static const int i=20;               };template<>struct Type<int>{                 static const int i=1;               };template<>struct Type<char>{                 static const int i=2;               }; template <typename T>void add(T t){    if(Type<T>::i==1)     cout<<"int"<<endl;    if(Type<T>::i==2)     cout<<"char"<<endl;}              int main(){        char ch='a';    add(ch);        system("pause");    return 0;}
[解决办法]
没办法直接知道,但是有N种方法可以绕过去,前提是得知道你到底想干什么。

 猜测你可能想要这种效果

template <typename T>
void add(T t)
{
}

template <>
void add<float>(float t) {}

template <>
void add<int>(int t) {}
[解决办法]
顶一下楼上,不过直接写,就可以了,不用去特化,而且不知道会不会有编译器不支持呢,
但是编译器会优先选择能精确匹配的函数,最后都无法匹配时才进行模板的推导。
template <typename T>
void add(T t)
{
std::cout<<"call gereral add"<<std::endl;
}

template<>
void add<float>(float t) 
{
std::cout<<"call special float add"<<std::endl;
}

void add(float t) 
{
std::cout<<"call float add"<<std::endl;
}
void add(int t) 
{
std::cout<<"call int add"<<std::endl;
}

热点排行