c++ - How to inherit a member function so that it always returns a reference to the derived instance? -
i'm working on iterator family, iterator classes x
have x& operator++() {++x; return *this}
in common, seems idea place in common base class. unfortunately, return type changes, since should return reference derived class.
the following illustrates problem. f()
work, workarounds come g()
, h()
, not satisfactory:
struct { a& f() {return *this;} template <typename t> t& g() {return *(t*)this;} template <typename t> t& h(t& unused) {return *(t*)this;} }; struct b : { int x; b(int x) : x(x) {} }; int main() { b b(12); //b b1 = b.f(); // error: conversion 'a' non-scalar type 'b' requested b b2 = b.g<b>(); // works b b3 = b.h(b); // works }
is there way make b b1 = b.f();
work? maybe using c++11 features?
use crtp:
template<class derived> struct { derived& f() {return static_cast<derived&>(*this);} }; struct b : a<b> { int x; b(int x) : x(x) {} };
Comments
Post a Comment