これは設計上の問題です。
テンプレート クラスがあり、テンプレートの種類に応じてメソッドを追加したいと考えています。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>
{
public:
Vector<T>(const T x, const T y, const T z)
: BaseVector<T>(x, y, z)
{
}
};
template <>
class Vector<double> : public BaseVector<double>
{
public:
Vector<double>(const double x, const double y, const double z);
Vector<double>(const Vector<int> &other);
double norm() const;
};
BaseVector は単なる実装の詳細に過ぎないつもりです。これは機能しますが、私は心配していoperator+=
ます。私の質問は:this
ポインターの動的キャストはコードの匂いですか? 私がやろうとしていることを達成するためのより良い方法はありますか (コードの重複やユーザーコードでの不要なキャストを避けます)? それとも、BaseVector コンストラクターはプライベートなので安全ですか?
編集:
申し訳ありませんが、はい、仮想 dtor を持っていますが、貼り付けるのを忘れていました。コードはそれなしではコンパイルされません。