茂加部珈琲店

主にtech関連のメモ置き場です

型情報の保存

あけましておめでとうございます.

突然ですが、基底クラスから元の型を復元したいと思うことはないでしょうか.C++ではそのような型情報の保存を簡単に行えるみたいです.
具体的には、仮想関数を利用して型情報を返す関数を定義します.

#include <iostream>
#include <typeinfo>

struct Base{
    //型情報を返す仮想関数
    virtual const std::type_info& type() const{
        return typeid(*this);
    }
};

struct ClassA : public Base{
    
};


int main(){
    //基底クラス
    Base base;
    //派生クラス
    ClassA classA;
    //基底クラスのポインタに格納された派生クラス
    Base* base_classA = &classA;

    std::cout << "type of base is " << base.type().name() << std::endl;
    std::cout << "type of classA is " << classA.type().name() << std::endl;
    std::cout << "type of base_classA is " << base_classA->type().name() << std::endl;

    return 0;
}

/* 実行結果:
type of base is 4Base
type of classA is 6ClassA
type of base_classA is 6ClassA
*/

このようにして、仮想関数を使うことで、基底クラスのポインタからも元の型名が取り出せます.
typeinfoが致すればキャストするようにすれば、比較的安全に型が復元できるはずですね.
このテクニックはboostライブラリのboost::anyでも使用されているようです.