使用typeid检查模板类型

tve*_*y42 1 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;
}
Run Code Online (Sandbox Code Playgroud)

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

我创建了一个模板类参数.

我知道如果我的参数不是我预期的3种类型中的一种,那么它将失败.但这不是问题,因为我知道参数只能是这些类型.

谢谢你的帮助

Dan*_*rey 5

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

this->mstrings[p.name()] = p;
Run Code Online (Sandbox Code Playgroud)

该类型的mstrings很可能不符合合格Parameter<int>p,因此,你会得到一个编译错误.

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

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

同样适用于其他情况.

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