Posts c++11 shared_ptr 类型转换
Post
Cancel

c++11 shared_ptr 类型转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <memory>
#include <iostream>
#include <type_traits>
 
class base{
 public:
    base(){std::cout << "base" << std::endl;}
    ~base(){std::cout << "~base" << std::endl;}
    void print(){std::cout << "base::print" << std::endl;}
};
 
class derived:public base{
 public:
    derived(){std::cout << "derived" << std::endl;}
    ~derived(){std::cout << "~derived" << std::endl;}
    void print(){std::cout << "derived::print" << std::endl;}
};
 
template<typename T>
std::shared_ptr<
    typename std::enable_if<(!std::is_same<base,T>::value)
                            &&(std::is_base_of<base,T>::value),T>::type
>
dyn_cast(std::shared_ptr<base> ptr){
    return std::static_pointer_cast<T>(ptr);
}
 
int main()
{
    std::shared_ptr<base> b_ptr = std::make_shared<derived>();
    b_ptr->print();
    auto d_ptr = dyn_cast<derived>(b_ptr);
    d_ptr->print();
    return 0;
}

This post is licensed under CC BY 4.0 by the author.