相关疑难解决方法(0)

可以动态转换“this”作为返回值吗?

这更多的是一个设计问题。

我有一个模板类,我想根据模板类型向其添加额外的方法。为了实践 DRY 原则,我提出了这个模式(有意省略定义):

template <class T>
class BaseVector: public boost::array<T, 3>
{
protected:
    BaseVector<T>(const T x, const T y, const T z);
public:
    bool operator == (const Vector<T> &other) const;
    Vector<T> operator + (const Vector<T> &other) const;    
    Vector<T> operator - (const Vector<T> &other) const;
    Vector<T> &operator += (const Vector<T> &other)
    {
        (*this)[0] += other[0];
        (*this)[1] += other[1];
        (*this)[2] += other[2];

        return *dynamic_cast<Vector<T> * const>(this);
    }

    virtual ~BaseVector<T>()
    {
    }
}

template <class T>
class Vector : public BaseVector<T>
{ …
Run Code Online (Sandbox Code Playgroud)

c++ templates design-patterns dynamic-cast this

4
推荐指数
1
解决办法
2096
查看次数

标签 统计

c++ ×1

design-patterns ×1

dynamic-cast ×1

templates ×1

this ×1