[C++]Covariant return types

前端 未结 2 1875
南旧
南旧 2020-12-11 08:55

I have a VectorN class, and a Vector3 class inherited from VectorN (which can handle cross products for example). I have trouble deter

相关标签:
2条回答
  • 2020-12-11 09:06

    You need a re-design. First, prefer free-functions over member-functions. The only member functions you should have are the ones that need access to privates.

    Start with this combo:

    class VectorN
    {
    public:
       virtual VectorN& operator*=(double d)
        {
            /* ... */
    
            return *this;
        };
    };
    
    
    class Vector3 : public VectorN
    {
    public:
        virtual Vector3& operator*=(double d)
        {
            return static_cast<Vector3&>(VectorN::operator*=(d));
        };
    };
    

    Here covariance works fine because the type is a reference or pointer, and you re-use code. (static_cast is free, performance-wise, and safe since you know the derived type.)

    Then you implement your free-functions:

    // optimization: if you're going to make a copy, do it in the parameter list;
    // compilers can elide a copy when working with temporaries
    VectorN operator*(VectorN v, double d)
    {
        // reuse code
        return v *= d;
    }
    
    VectorN operator*(double d, VectorN v)
    {
        // reuse code
        return v *= d;
    }
    

    Do the same with Vector3.

    What's been done is you get an easy way to write these operators because you get to use the core of the operator, and the return type matches, thanks to covariance.


    Do heed warnings though, you probably don't need any of it. And extensions you want to make can be made via free-functions operating on a vector or valarray.

    0 讨论(0)
  • 2020-12-11 09:21

    The best I can think of is to replace the return type with a smart pointer and forgo covariance in favor of polymorphism:

    virtual auto_ptr< VectorN > operator*(const double& d);
    

    The reason I suggest this is that you are using virtual functions, so knowing the exact type of the object isn't necessary anyway.

    The underlying problem is that the caller needs to allocate storage for an object returned by value. That storage cannot vary dynamically, so you are inevitably stuck allocating the object on the heap.

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