我正在寫一個模板矢量型簡單的數學庫:具有共享功能的類模板特
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
,然後再返回。儘管內存中的類型是相同的,編譯器可能會優化所有這些,但感覺笨重,我不太希望在本質上是編譯時問題的情況下有潛在的運行時間開銷。
有沒有其他方法可以解決這個問題?
爲什麼不只是製作'x()'和'y()'免費函數,採用適當的「Vector」特化?例如。 'template T x(const Vector & v);' –
2010-05-03 12:10:41
可能的,但是'vx()'對我來說比'x(v)'更有意義另外,我想添加一些專門的構造函數,例如'Vector( T,T)',並且構造函數不能是自由函數 –
Thomas
2010-05-03 12:17:56
不,但是你可以有函數按'std :: make_pair'的樣式按值返回對象 – 2010-05-03 12:25:15