且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用typeid检查模板类型

更新时间:2023-11-30 20:22:58

代码不会编译,而不是因为 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.