How can I use covariant return types with smart pointers?

后端 未结 7 1476
囚心锁ツ
囚心锁ツ 2020-11-27 17:42

I have code like this:

class RetInterface {...}

class Ret1: public RetInterface {...}

class AInterface
{
  public:
     virtual boost::shared_ptr

        
相关标签:
7条回答
  • 2020-11-27 18:33

    Firstly, this is indeed how it works in C++: the return type of a virtual function in a derived class must be the same as in the base class. There is the special exception that a function that returns a reference/pointer to some class X can be overridden by a function that returns a reference/pointer to a class that derives from X, but as you note this doesn't allow for smart pointers (such as shared_ptr), just for plain pointers.

    If your interface RetInterface is sufficiently comprehensive, then you won't need to know the actual returned type in the calling code. In general it doesn't make sense anyway: the reason get_r is a virtual function in the first place is because you will be calling it through a pointer or reference to the base class AInterface, in which case you can't know what type the derived class would return. If you are calling this with an actual A1 reference, you can just create a separate get_r1 function in A1 that does what you need.

    class A1: public AInterface
    {
      public:
         boost::shared_ptr<RetInterface> get_r() const
         {
             return get_r1();
         }
         boost::shared_ptr<Ret1> get_r1() const {...}
         ...
    };
    

    Alternatively, you can use the visitor pattern or something like my Dynamic Double Dispatch technique to pass a callback in to the returned object which can then invoke the callback with the correct type.

    0 讨论(0)
提交回复
热议问题