Skip to content

Instantly share code, notes, and snippets.

@usagi
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

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

Select an option

Save usagi/9188550 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(); }
};
#include "enable_shared_from_this_wrap.hxx"
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();
}
@usagi

usagi commented Feb 24, 2014

Copy link
Copy Markdown
Author

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