简体   繁体   中英

method chaining child with parent classes using c++

Is there a way to chain calls to superclass from subclass without casting, overriding the method or using interfaces. Eg when doing

class A {
public: 
    A& foo() { return *this; }
};

class B : public A {
public:
    B& bar() { return *this; }
};

int main(void) {
    B b;
    b.foo().bar();
    return 0;
}

When compiling with clang I'm getting the error

main.cpp:13:10: error: no member named 'bar' in 'A'
        b.foo().bar();
        ~~~~~~~ ^
1 error generated.

Which I can see why (since A returns reference to self), but I would like it to return it's subclass type B since it is called in that context. Is this possible? Or do I need to define B as

class B : public A {
public:
    B& bar() { return *this; }
    B& foo() { A::foo(); return *this; }
};

and make foo() virtual?

You can use CRTP pattern:

template<class Derived>
class A {
public:
    Derived& foo() { return *static_cast<Derived*>(this); }
};

class B : public A<B> {
public:
    B& bar() { return *this; }
};

int main(void) {
    B b;
    b.foo().bar();
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM