使用typeid检查模板类型

时间:2014-09-16 15:56:07

标签: c++ templates typeid

我想知道如果做以下事情是安全的:

template<class T>
void Parameters::add(Parameter<T> p)
{
   std::string sprobe("");
   int iprobe = 0;
   double dprobe = 0.;

   if (typeid(T) == typeid(sprobe))
     this->mstrings[p.name()] = p;

   if (typeid(T) == typeid(iprobe))
     this->mints[p.name()] = p;

   if (typeid(T) == typeid(dprobe))
     this->mdoubles[p.name()] = p;
}

我有一个用于存储参数的类。它有3个boost :: unordered_map成员变量,用于存储int,double和std :: string类型的参数;

我创建了一个模板类Parameter。

据我所知,如果我的参数不是我预期的3种类型中的一种,则会失败。但这不是问题,因为我知道参数只能是这些类型。

感谢您的帮助

2 个答案:

答案 0 :(得分:5)

代码不会编译,但不会因为typeid而编译。问题是即使使用正确的if - 子句,也需要编译方法的代码 - 所有这些代码。这与代码的一部分是否被执行(=已评估)无关。这导致了如果Tint,您仍然需要能够为其他情况编译代码的问题,例如,此行:

this->mstrings[p.name()] = p;

mstrings的类型很可能与将Parameter<int>作为p传递不兼容,因此您将收到编译错误。

解决方案是使用重载,其中每个方法只能编译一个案例,而不能编译其他案例,例如int

void Parameters::add(Parameter<int> p)
{
    this->mints[p.name()] = p;
}

同样适用于其他案件。

最后注意事项:即使您使用typeid,也不需要探测器。您可以直接使用typeid(int)

答案 1 :(得分:0)

忽略这是否是一种良好的编程习惯......

从语言的角度来看,您的程序是安全的。 type_info运算符返回的typeid的比较在标准中有明确定义:

  

18.5.1 Class type_info

     

...

     

bool operator==(const type_info& rhs) const;

     

2 效果:将当前对象与 rhs 进行比较。

     

3 如果两个值描述相同的类型,则返回 true

相关问题