我熟悉C++ RTTI,发现这个概念很有意思.
仍然存在许多滥用它的方法而不是正确使用它(RTTI-switch恐惧会浮现在脑海中).作为开发人员,我发现(并且使用过)只有两种可行的用途(更确切地说,一个半).
您能否分享一些RTTI是问题的可行解决方案,包括示例代码/伪代码?
注意:目标是拥有一个可供初级开发人员可以咨询,批评和学习的可行示例的存储库.
编辑:您将使用C++ RTTI找到下面的代码
// A has a virtual destructor (i.e. is polymorphic)
// B has a virtual destructor (i.e. is polymorphic)
// B does (or does not ... pick your poison) inherits from A
void doSomething(A * a)
{
// typeid()::name() returns the "name" of the object (not portable)
std::cout << "a is [" << typeid(*a).name() << "]"<< std::endl ;
// the dynamic_cast of a pointer to another will return NULL is
// the conversion is not possible
if(B * b = dynamic_cast<B *>(a))
{
std::cout << "a is b" << std::endl ;
}
else
{
std::cout << "a is NOT b" << std::endl ;
}
}
Run Code Online (Sandbox Code Playgroud)
boost :: any对象怎么样!
这基本上使用RTTI信息来存储任何对象,并检索该对象使用boost :: any_cast <>.
您可以将RTTI与dynamic_cast一起使用以获取指向派生类的指针,以便使用它来调用快速的类型专用算法.而不是通过基类使用虚方法,它将进行直接和内联调用.
使用GCC为我加速了很多事情.Visual Studio似乎没有那么好,它可能有一个较慢的dynamic_cast查找.
例:
D* obj = dynamic_cast<D*>(base);
if (obj) {
for(unsigned i=0; i<1000; ++i)
f(obj->D::key(i));
}
} else {
for(unsigned i=0; i<1000; ++i)
f(base->key(i));
}
}
Run Code Online (Sandbox Code Playgroud)
我不能说我曾经在现实生活中找到过使用但是在Effective C++中提到RTTI 作为C++中多方法的可能解决方案.这是因为方法调度是在this参数的动态类型上完成的,但是参数的静态类型.
class base
{
void foo(base *b) = 0; // dynamic on the parameter type as well
};
class B : public base {...}
class B1 : public B {...}
class B2 : public B {...}
class A : public base
{
void foo(base *b)
{
if (B1 *b1=dynamic_cast<B1*>(b))
doFoo(b1);
else if (B2 *b2=dynamic_cast<B2*>(b))
doFoo(b2);
}
};
Run Code Online (Sandbox Code Playgroud)