Is there a way to forward declare covariance?

后端 未结 4 1462
别跟我提以往
别跟我提以往 2021-02-19 02:02

Suppose I have these abstract classes Foo and Bar:

class Foo;
class Bar;

class Foo
{
public:
  virtual Bar* bar() = 0;
};

class Bar
{         


        
4条回答
  •  终归单人心
    2021-02-19 02:33

    You can fake it quite easily, but you lose the static type checking. If you replace the dynamic_casts by static_casts, you have what the compiler is using internally, but you have no dynamic nor static type check:

    class Foo;
    class Bar;
    
    class Foo
    {
    public:
      Bar* bar();
    protected:
      virtual Bar* doBar();
    };
    
    class Bar;
    {
    public:
      Foo* foo();
    public:
      virtual Foo* doFoo();
    };
    
    inline Bar* Foo::bar() { return doBar(); }
    inline Foo* Bar::foo() { return doFoo(); }
    
    class ConcreteFoo;
    class ConcreteBar;
    class ConcreteFoo : public Foo
    {
    public:
      ConcreteBar* bar();
    protected:
      Bar* doBar();
    };
    
    class ConcreteBar : public Bar
    {
    public:
       ConcreteFoo* foo();
    public:
       Foo* doFoo();
    };
    
    inline ConcreteBar* ConcreteFoo::bar() { return &dynamic_cast(*doBar()); }
    inline ConcreteFoo* ConcreteBar::foo() { return &dynamic_cast(*doFoo()); }
    

提交回复
热议问题