[enable_shared_from_this] My derivation of enable_shared_from_this wants to be templated

Here's some code based upon the example at : http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/enable_shared_from_this.... class X { public: X() { }; }; template<class X> class Y: public enable_shared_from_this< Y<X> > { public: shared_ptr< Y<X> > f() { return shared_from_this(); } }; typedef Y<X> templatedY; int main() { shared_ptr<templatedY> p(new Y<X>); shared_ptr<templatedY> q = p->f(); assert(p == q); assert(!(p < q || q < p)); // p and q must share ownership } compiles with: $ gcc -o test -I/usr/local/include/boost-1_38 -lstdc++ -L/usr/local/lib -lboost_system-gcc41-mt test.cpp test.cpp: In member function âboost::shared_ptr<Y<X> > Y<X>::f()â: test.cpp:13: error: there are no arguments to âshared_from_thisâ that depend on a template parameter, so a declaration of âshared_from_thisâ must be available test.cpp:13: error: (if you use â-fpermissiveâ, G++ will accept your code, but allowing the use of an undeclared name is deprecated) Any resolution (other than the -fpermissive hack) TIA (my skilz with shared_ptr<> are somewhat lacking ...)

Rob Currey:
template<class X> class Y: public enable_shared_from_this< Y<X> > { public:
shared_ptr< Y<X> > f() { return shared_from_this();
In a template, you need return this->shared_from_this(); to inform the compiler that shared_from_this will come from a base class.
} };
participants (2)
-
Peter Dimov
-
Rob Currey