chikuchikugonzalezの雑記帳

趣味とか日記とかメモとか(∩゚д゚)

std::shared_ptrで親子関係にある型のキャスト.

テンプレート化されたクラスはテンプレートパラメータが親子関係でも別クラスなので代入できねぇ、とか思ってたんですがshared_ptrでふつーにできたり、キャストする方法があって(´・∀・`)ヘー って思ったのでメモしておかなきゃ

#include <memory>
#include <iostream>

class Base {
public:
    virtual void hello() {
        std::cout << "Hello in Base!" << std::endl;
    }
};
class Sub : public Base {
public:
    virtual void hello() override {
        std::cout << "Hello in Sub!" << std::endl;
    }
};

int main(void) {
    std::shared_ptr<Base> p1 = std::make_shared<Base>();
    std::shared_ptr<Sub>  p2 = std::make_shared<Sub>();
    std::shared_ptr<Base> p3 = std::make_shared<Sub>();
    std::shared_ptr<Sub>  p4 = std::dynamic_pointer_cast<Sub>(p3);

    p1->hello();    // => Hello in Base!
    p2->hello();    // => Hello in Sub!
    p3->hello();    // => Hello in Sub!
    p4->hello();    // => Hello in Sub!

    return 0;

リファレンス見たら dynamic_cast 以外のキャストも全部専用のがあるっぽいね

Specific functions:

make_shared Make shared_ptr (function template )
allocate_shared Allocate shared_ptr (function template )
static_pointer_cast Static cast of shared_ptr (function template )
dynamic_pointer_cast Dynamic cast of shared_ptr (function template )
const_pointer_cast Const cast of shared_ptr (function template )
get_deleter Get deleter from shared_ptr (function template )
shared_ptr - C++ Reference