如何继承成员函数,以便始终返回对派生实例的引用?

Ste*_*fan 4 c++ polymorphism inheritance templates c++11

我正在开发一个迭代器系列,其中所有迭代器类X都有X& operator++() {++x; return *this}共同点,因此将它放在一个公共基类中似乎是个好主意.不幸的是,返回类型会发生变化,因为它应该始终返回对派生类的引用.

以下说明了这个问题.我想f()工作,但唯一的解决方法我能想出是g()h(),这是不令人满意的:

struct A {
    A& f() {return *this;}

    template <typename T>
    T& g() {return *(T*)this;}

    template <typename T>
    T& h(T& unused) {return *(T*)this;}
};

struct B : A {
    int x;
    B(int x) : x(x) {}
};

int main() {
    B b(12);

    //B b1 = b.f();   // error: conversion from 'A' to non-scalar type 'B' requested

    B b2 = b.g<B>();  // works
    B b3 = b.h(b);    // works
}
Run Code Online (Sandbox Code Playgroud)

有办法B b1 = b.f();上班吗?也许使用C++ 11功能?

eca*_*mur 13

使用CRTP:

template<class Derived>
struct A {
    Derived& f() {return static_cast<Derived&>(*this);}
};

struct B : A<B> {
    int x;
    B(int x) : x(x) {}
};
Run Code Online (Sandbox Code Playgroud)