2010年5月23日日曜日

C++でオブジェクトのクラス名(型名)文字列を実行時に取得する

今日はC++オブジェクトクラス名を実行時に取得する方法を紹介します。
紹介するといってもtypeid()という関数を使用するだけです。typeid()はtypeinfo.hで定義されているのでincludeする必要があります。
typeid()の引数には変数オブジェクトや型名(クラス名)を直接指定することが出来ます。
またtypeid()の戻り値同士を比較したりも出来ます。

サンプルコードを用意しました。

main.cpp
  1. #include <stdio.h>  
  2. #include <typeinfo>  
  3. #include "ConcreteClass.h"  
  4.   
  5. void main(void)  
  6. {  
  7.     //  ConcreteClassオブジェクト生成  
  8.     AbstractClass* obj = new ConcreteClass();  
  9.   
  10.     //  型名取得  
  11.     const type_info& id = typeid(*obj);  
  12.     printf("%s\n", id.name());  
  13.   
  14.     //  method()の呼び出し  
  15.     obj->method();  
  16.   
  17.     //  型を直接指定し型名を取得し比較  
  18.     if (typeid(ConcreteClass) == id) {  
  19.         printf("true\n");  
  20.     }  
  21.   
  22.     delete obj;  
  23.   
  24.     printf("hit any key...\n");  
  25.     while(getchar() == EOF) {}  
  26. }  
  27. </typeinfo></stdio.h>  

AbstractClass.h
  1. #ifndef _ABSTRACT_CLASS_H_  
  2. #define _ABSTRACT_CLASS_H_  
  3.   
  4. #include <stdio.h>  
  5. #include <typeinfo.h>  
  6.   
  7. class AbstractClass  
  8. {  
  9.     //----------------------------------  
  10.     //  method  
  11.     //----------------------------------  
  12. public:  
  13.     void method() {  
  14.         //  型情報の取得  
  15.         const type_info& id = typeid(*this);  
  16.   
  17.         //  表示  
  18.         printf("AbstractClass-typeid:%s\n", id.name());  
  19.   
  20.         //  subMethod()の呼び出し  
  21.         this->subMethod();  
  22.     }  
  23.   
  24. protected:  
  25.     virtual void subMethod() = 0;  
  26. };  
  27. #endif  
  28. </typeinfo.h></stdio.h>  

ConcreteClass.h
  1. #ifndef _CONCRETE_CLASS_H_  
  2. #define _CONCRETE_CLASS_H_  
  3.   
  4. #include <stdio.h>  
  5. #include <typeinfo.h>  
  6. #include "AbstractClass.h"  
  7.   
  8. class ConcreteClass : public AbstractClass  
  9. {  
  10.  //----------------------------------  
  11.  // method  
  12.  //----------------------------------  
  13. public:  
  14.  ConcreteClass() {  
  15.   // do nothing...  
  16.  }  
  17.   
  18.  virtual ~ConcreteClass() {  
  19.   // do nothing...  
  20.  }  
  21.   
  22. protected:  
  23.  virtual void subMethod() {  
  24.   // 型情報の取得  
  25.   const type_info& id = typeid(*this);  
  26.   
  27.   // 表示  
  28.   printf("ConcreteClass-type_id:%s\n", id.name());  
  29.  }  
  30.   
  31. };  
  32. #endif  
  33. </typeinfo.h></stdio.h>  

0 件のコメント:

コメントを投稿