私は C++ RTTI に精通しており、その概念は興味深いと思います。
それでも、正しく使用するよりも悪用する方法の方がはるかに多く存在します (RTTI スイッチの恐怖が思い浮かびます)。開発者として、私はこれの有効な使用法を 2 つだけ見つけ (そして使用しました) (正確には 1 つ半) ました。
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 ;
}
}
ベストアンサー1
非循環ビジター(pdf) はそれをうまく活用したものです。