且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从派生类中引用基类成员

更新时间:2023-02-13 09:32:48

一个选项是创建一个存根类,子对象:

One option would be to create a stub class that you can use for casting to the right base class subobject:

struct A {
    void fa() { }
};

struct B : A {
    void fb() { }
};

// Use a stub class that we can cast through:
struct A_ : A { };

struct C : A_, B {
    void fc() {
        implicit_cast<A_&>(*this).fa();
    }
};

其中 implicit_cast 定义为:

template <typename T> struct identity { typedef T type; }

template <typename T>
T implicit_cast(typename identity<T>::type& x) { return x; }