我正在写一个模板矢量型简单的数学库:具有共享功能的类模板特
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