我熟悉 C++ RTTI,觉得这个概念很有趣。
仍然存在很多滥用它的方法而不是正确使用它(RTTI 切换恐惧浮现在脑海中)。作为一名开发人员,我发现(并使用)了它只有两种可行的用途(更准确地说是一种半)。
您能否分享一些 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 ;
}
}
最佳答案
Acyclic Visitor (pdf) 是一个很好的用途。
关于C++ RTTI 可行的例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/238452/