@ecatmur , , , , CRTP . , 2 :
template <typename D>
struct A {
D& f() {return *static_cast<D*>(this);}
};
template <typename D>
struct B : A<D> {
int x;
B(int x=0) : x(x) {}
};
struct C : B<C> {
double y;
C(double y=0.) : y(y) {}
};
int main() {
C c(12.5);
C c1 = c.f();
}
, C, B:
int main() {
B<B> b;
}
, typename template, B. :
template <typename D=B> struct B : A<D> {};
Thus, CRTP seems to be just a good idea in single inheritance situations.
I ended up with a simple solution to just return a reference to the base class A&. Since there is no loss of information in this way, derived classes can always discard the returned reference to the derived type:
struct A {
A& f() {return *this;}
};
struct B : A {
int x;
B(int x=0) : x(x) {}
};
struct C : B {
double y;
C(double y=0.) : y(y) {}
};
int main() {
B b(12);
B b1 = (B&)b.f();
C c(12.5);
C c1 = (C&)c.f();
}
So, it seems right to just return the reference to the base class and, if necessary, add it to the derived classes.
source
share