使用typeid检查模板类型 [英] Using typeid to check for template type

查看:626
本文介绍了使用typeid检查模板类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如果进行以下操作是安全的:

I would like to know if doing the following is safe:

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的参数;

I have a Class for storing parameters. It has 3 boost::unordered_map member variables for storing parameters of type int, double and std::string;

我创建了一个模板类Parameter。

I created a template class Parameter.

我理解如果我的参数不是我预期的3种类型之一,这将失败。但它不是一个问题,因为我知道参数只能是这些类型。

I understand that if my Parameter is not one of the 3 types that I anticipated this will fail. But it is not a problem since I know that the Parameters can only be of these types.

感谢您的帮助

推荐答案

代码不会编译,而不是因为 typeid 。问题是,即使使用正确的如果 -clauses,您的方法的代码需要编译 - 所有。这与代码的一部分是否被执行(=被评估)无关。这导致的问题是,如果 T int ,您仍然需要能够编译另一个例如,此行:

The code won't compile, but not because of typeid. The problem is that even with the correct if-clauses, the code of your method needs to be compiled - all of it. That is independent of whether or not a part of the code is executed (=evaluated) or not. This leads to the problem that if T is int, you still need to be able to compile the code for the other cases, e.g., this line:

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

mstrings 的类型很可能不兼容将参数作为 p ,因此您将收到编译错误。

The type of mstrings is very likely incompatible with passing Parameter<int> as p, hence you will get a compile error.

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

The solution is to use overloading where each method must only compile one case, but not the others, example for int:

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

,对于其他情况也是如此。

and likewise for the other cases.

最后一点:即使你使用 typeid ,你也不需要探针。您可以直接使用 typeid(int)

Final note: Even if you use typeid, you don't need the probes. You can simply use typeid(int) directly.

这篇关于使用typeid检查模板类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆