静的キャストを使用して継承階層をナビゲートする方が動的キャストを使用するよりも効率的であると述べているC++に関する1冊の本を見ました。
例:
#include <iostream>
#include <typeinfo>
using namespace std;
class Shape { public: virtual ~Shape() {}; };
class Circle : public Shape {};
class Square : public Shape {};
class Other {};
int main() {
Circle c;
Shape* s = &c; // Upcast: normal and OK
// More explicit but unnecessary:
s = static_cast<Shape*>(&c);
// (Since upcasting is such a safe and common
// operation, the cast becomes cluttering)
Circle* cp = 0;
Square* sp = 0;
// Static Navigation of class hierarchies
// requires extra type information:
if(typeid(s) == typeid(cp)) // C++ RTTI
cp = static_cast<Circle*>(s);
if(typeid(s) == typeid(sp))
sp = static_cast<Square*>(s);
if(cp != 0)
cout << "It's a circle!" << endl;
if(sp != 0)
cout << "It's a square!" << endl;
// Static navigation is ONLY an efficiency hack;
// dynamic_cast is always safer. However:
// Other* op = static_cast<Other*>(s);
// Conveniently gives an error message, while
Other* op2 = (Other*)s;
// does not
} ///:~
ただし、動的キャストと静的キャスト(上記で実装)の両方で、このようなナビゲーションを機能させるにはRTTIを有効にする必要があります。動的キャストでは、クラス階層が多態的である必要があります(つまり、少なくとも1つの仮想関数を持つ基本クラス)。
静的キャストのこの効率の向上はどこから来るのですか?この本は、動的キャストがタイプセーフなダウンキャストを行うための好ましい方法であると述べています。