Interfaces and covariance problem

前端 未结 5 2081
我在风中等你
我在风中等你 2021-01-05 07:29

I have a particular class that stores a piece of data, which implements an interface:

template
class MyContainer : public Container

        
5条回答
  •  感动是毒
    2021-01-05 08:06

    Have you thought about using CRTP. I find it a good candidate here. Here is a brief demo. It just explains your ++retval problem (if I understood it correctly). You have to change your IInterface definition from pure virtual to CRTP type interface.

    template
    struct IInterface
    {
      Derived& operator ++ ()
      {
        return ++ *(static_cast(this));
      }
    };
    
    struct Something : public IInterface
    {
      int x;
      Something& operator ++ ()
      {
        ++x;
        return *this;
      }
    };
    

    There are some limitations of CRTP, that the template will always follow your IInterface. Which means that if you are passing a Something object to a function like this:

    foo(new Something);
    

    Then, foo() should be defined as:

    template
    void foo(IInterface *p)
    {
      //...
      ++(*p);
    }
    

    However for your problem, it can be a good fit.

提交回复
热议问题