Skip to content

Instantly share code, notes, and snippets.

@usagi
Created April 7, 2014 06:55
Show Gist options
  • Select an option

  • Save usagi/10015807 to your computer and use it in GitHub Desktop.

Select an option

Save usagi/10015807 to your computer and use it in GitHub Desktop.
#include <memory>
template<class T_derived, class T_base = void>
class enable_shared_from_this_wrap: public T_base
{
public:
std::shared_ptr<T_derived> shared_from_this()
{ return std::static_pointer_cast<T_derived>(T_base::shared_from_this_wrap()); }
std::shared_ptr<T_derived const> shared_from_this() const
{ return std::static_pointer_cast<T_derived const>(T_base::shared_from_this_wrap()); }
};
template<class T_derived>
class enable_shared_from_this_wrap<T_derived, void>
: public std::enable_shared_from_this<T_derived>
{
using base_type = std::enable_shared_from_this<T_derived>;
protected:
std::shared_ptr<T_derived> shared_from_this_wrap()
{ return base_type::shared_from_this(); }
std::shared_ptr<T_derived const> shared_from_this_wrap() const
{ return base_type::shared_from_this(); }
};
class A: public enable_shared_from_this_wrap<A>
{
public:
void fa(){}
};
class B: public enable_shared_from_this_wrap<B, A>{
public:
void fb(){}
};
int main()
{
auto b = std::make_shared<B>();
b->shared_from_this()->fa();
b->shared_from_this()->fb();
// A a1;
// a1.shared_from_this()->fa(); // throw bad_weak_ptr!
// A* a2(new A);
// a2->shared_from_this()->fa(); // throw bad_weak_ptr!
}
@usagi

usagi commented Apr 7, 2014

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment