LoginSignup
29
23

More than 5 years have passed since last update.

C++でクラス名を取得する

Last updated at Posted at 2013-05-31

C++で、typeid()とabi::__cxa_demangle()を使って実行時に型情報を取得した時のメモ。

#include <string>
#include <typeinfo>
#include <cxxabi.h>

class Foo;

{
    Foo obj;
    const type_info& id = typeid(obj);
    int stat;
    char *name = abi::__cxa_demangle(id.name(),0,0,&stat);
    if( name!=NULL ) {
        if( stat==0) {    // ステータスが0なら成功
            printf("name=%s",name);
        }
        free(name);        // freeする必要がある
    }

}

こんな感じで、typeid()で型情報を取得するのですが、そのままではマングリングされています。
デマングル処理を行う事で、クラス名を取得できるようになります。

※追記
__cxa_demangle()は明示的にfreeする必要があるそうです。下記参照。
http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html

A pointer to the start of the NUL-terminated demangled name, or NULL if the demangling fails.
The caller is responsible for deallocating this memory using free.

29
23
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
23