Saturday, 15 June 2013

c++ - Curiously Recurring Template and Template parameter dependent subclassing issues -



c++ - Curiously Recurring Template and Template parameter dependent subclassing issues -

i trying create next code work

template < class __derived, class __object = typename __derived::object > struct base of operations { using derived = __derived; using object = __object; void function(object o) { homecoming derived::function(s); } } //template < class __derived > //struct base of operations { // using derived = __derived; // using object = typename derived::object; // void function(object o) { homecoming derived::function(s); } //} template < class __object > struct derived : public base< derived< __object > > { using object = __object; void function(object o) { ... } }

and instantiate object declaring

derived<double> obj;

problem is, compiler claims not able find symbol object within derived class while deducing sec template parameter base class. same error generated commented version.

i trying under inspiration of eigen3 code, particularly crtp (curiously recurring template pattern) utilize in order avoid utilize of virtual functions. eigen3 uses traits class can't figure out how imitate nowadays case. has suggestion this? in advance!

normally, if want inherit b, b cannot know other it's declaration:

template < class __object > struct derived;

unfortunately, want more, you'll have utilize type trait:

template<class __derived> struct base_traits { //using object = ?????; }; template<class __object> struct base_traits<derived<__object>> { using object = __object; //note, can't inspect b. };

the base class can inspect base_traits wants, because traits don't inspect b @ all.

template < class __derived, class __object = typename base_traits<__derived>::object > struct base of operations { using derived = __derived; using object = typename base_traits<__derived>::object; //or using object = __object;

unrelated, leading double underscores disallowed utilize mortals, utilize single leading underscore followed lowercase letter. alternatively, utilize trailing underscore.

also, syntax

void function(object o) { homecoming derived::function(s); }

won't work, because notation cannot used upcasts, downcasts. ergo, have utilize static_cast on this. since that's vaguely ugly, set behind function:

void foo(object o) { self()->bar(o); } private: __derived* self() {return static_cast<__derived*>(this);} const __derived* self() const {return static_cast<__derived*>(this);} };

full code: http://coliru.stacked-crooked.com/a/81595b0fcd36ab93

c++ templates subclassing crtp

No comments:

Post a Comment