C++专业化,type_of或只是typeid

fay*_*aya 2 c++ types specialization

我想知道在我的情况下使用什么更好以及为什么.首先,我听说使用RTTI(typeid)很糟糕.有谁能解释为什么?如果我确切地知道类型在运行时比较它们有什么问题?还有什么例子如何使用boost :: type_of?我发现没有人通过强大的谷歌搜索:)其他解决方案对我来说是专业化,但我会专注于至少9种类型的新方法.这是我需要的一个例子:

我有这门课

  template<typename A, typename B, typename C>
  class CFoo
  {
     void foo()
     {
       // Some chunk of code depends on old A type
     }

  }
Run Code Online (Sandbox Code Playgroud)

所以我需要更确切地检查typeid(我听到的是BAD)并在示例中进行以下3个实现:

 void foo()
   {
      if (typeid(A) == typeid(CSomeClass)
       // Do this chunk of code related to A type
      else
      if (typeid(B) == typeid(CSomeClass)
       // Do this chunk of code related to B type
      else
      if (typeid(C) == typeid(CSomeClass)
       // Do this chunk of code related to C type
   }
Run Code Online (Sandbox Code Playgroud)

那么什么是最好的解决方案?我不想专注于所有A,B,C,因为每种类型都有3个特化,所以我将得到9个方法或只是这个类型检查.

sel*_*tze 6

这很糟糕,因为

  1. A,B和C在编译时是已知的,但您使用的是运行时机制.如果调用typeid,编译器将确保将元数据包含在目标文件中.
  2. 如果用实际使用CSomeClass接口的代码替换"执行与A类型相关的这一部分代码",您将看到在A!= CSomeClass和A具有不兼容接口的情况下,您将无法编译代码.编译器仍尝试转换代码,即使它从未运行过.(见下面的例子)

您通常所做的是将代码分解为单独的函数模板或可以专用的类的静态成员函数.

坏:

template<typename T>
void foo(T x) {
    if (typeid(T)==typeid(int*)) {
        *x = 23; // instantiation error: an int can't be dereferenced
    } else {
        cout << "haha\n";
    }
}
int main() {
    foo(42); // T=int --> instantiation error
}
Run Code Online (Sandbox Code Playgroud)

更好:

template<typename T>
void foo(T x) {
    cout << "haha\n";
}
void foo(int* x) {
    *x = 23;
}
int main() {
    foo(42); // fine, invokes foo<int>(int)
}
Run Code Online (Sandbox Code Playgroud)

干杯,s