继承:返回自我类型的函数?

Gra*_*pes 11 c++

假设我有两个类:

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

class B:public class A
{
    public:
    B* World()
    {
        return this;
    }
}
Run Code Online (Sandbox Code Playgroud)

让我们说我有一个B像这样的类的实例:

B test;
Run Code Online (Sandbox Code Playgroud)

如果我打电话test.World()->Hello()说那会很好.但是test.Hello()->World()因为Hello()返回A类型不起作用.

Hello()该如何归还B?我不想使用virtual函数,因为我们有超过20个不同的类继承A.

mfo*_*ini 18

您可以使用CRTP,这是一个奇怪的重复模板模式:

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

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


int main() {
    B test;
    test.World()->Hello();
    test.Hello()->World();
}
Run Code Online (Sandbox Code Playgroud)

  • @antonm 这里的 A 是一个空类,所以 EBCO 在这里意味着没有开销。 (2认同)