2010年6月11日金曜日

typeid演算子

C++のお話。

Colladaを読んでいて、daeElement型で取得したポインタを実際の型にダウンキャストしなければならない事態に陥った。陥ったというか設計上やむなしといったところか。いずれにせよ、そういう事態になった。

Colladaでも型情報を文字列で返してくれるなど、親切なAPIは用意されていたのだが、せっかくなのでtypeidを使ってみることにした。



01#include <iostream>
02#include <typeinfo>
03using namespace std;
04 
05class Base
06{
07public:
08   virtual ~Base(){}//仮想関数を作っておかないと実行時型情報が作られないっぽい
09};
10class Sub1: public Base{};
11class Sub2: public Base{};
12 
13int main()
14{
15   Base *base = new Base();
16   Base *sub1 = new Sub1();
17   Base *sub2 = new Sub2();
18 
19   if(typeid(*base) == typeid(Base))
20   {
21      cout << "Yeah! I'm an instance of Base!!" << endl;
22   }
23    
24   if(typeid(*sub1) == typeid(Sub2))
25   {
26      cout << "Hi! I'm an instance of Sub2!!" << endl;
27   }
28   else
29   {
30      cout << "Boooo... I'm not an instance of Sub2!!" << endl;
31   }
32    
33   if(typeid(*sub2) == typeid(Sub2))
34   {
35      cout << "Hi! I'm an instance of Sub2!!" << endl;
36   }
37   else
38   {
39      cout << "Boooo... I'm not an instance of Sub2!!" << endl;
40   }
41 
42   delete base;
43   delete sub1;
44   delete sub2;
45 
46   return 0;
47}
実行結果は以下のとおり。
Yeah! I'm an instance of Base!!
Boooo... I'm not an instance of Sub2!!
Hi! I'm an instance of Sub2!!
実は最初試したときはvirtual関数を一つも書いていなかったので、POD型としてコンパイルされる->実行時型情報がとれないということになっていたっぽい。なので上記コードのvirtualなデストラクタは一見無意味ですが、つくっておかないと望んだ結果は得られません。まあ普通は作るよね…。

strcmpで比較するより短く書け、dynamic_castでいちいち型を調べていくより効率良さそうな方法だと思う。早速取り入れてみよう。

参考サイト

0 件のコメント:

コメントを投稿