私はテンプレートベクトルタイプで簡単な数学ライブラリを書いています:
template<typename T, size_t N>
class Vector {
public:
Vector<T, N> &operator+=(Vector<T, N> const &other);
// ... more operators, functions ...
};
今、私はこれらのいくつかのために特別にいくつかの追加機能が必要です。関数を使用して特定の座標にアクセスしたいx()
とy()
します。Vector<T, 2>
これのために部分的な特殊化を作成することができます:
template<typename T>
class Vector<T, 3> {
public:
Vector<T, 3> &operator+=(Vector<T, 3> const &other);
// ... and again all the operators and functions ...
T x() const;
T y() const;
};
しかし今、私は汎用テンプレートにすでに存在するすべてを繰り返しています。
継承も使用できます。汎用テンプレートの名前をに変更するとVectorBase
、次のようになります。
template<typename T, size_t N>
class Vector : public VectorBase<T, N> {
};
template<typename T>
class Vector<T, 3> : public VectorBase<T, 3> {
public:
T x() const;
T y() const;
};
ただし、問題は、すべての演算子がで定義されているため、インスタンスVectorBase
を返すことです。これらを変数VectorBase
に割り当てることはできません。Vector
Vector<float, 3> v;
Vector<float, 3> w;
w = 5 * v; // error: no conversion from VectorBase<float, 3> to Vector<float, 3>
Vector
これを可能にするために、暗黙の変換コンストラクターを与えることができます。
template<typename T, size_t N>
class Vector : public VectorBase<T, N> {
public:
Vector(VectorBase<T, N> const &other);
};
しかし、今、私はからVector
にVectorBase
、そしてまた戻って変換しています。型はメモリ内で同じであり、コンパイラはこれをすべて最適化する可能性がありますが、それは不格好に感じられ、本質的にコンパイル時の問題である潜在的な実行時のオーバーヘッドはあまりありません。
これを解決する他の方法はありますか?