【发布时间】:2011-12-27 13:20:11
【问题描述】:
我想创建一个通用向量类并为少数情况创建特化。像这样的东西(它不会编译,但希望能传达我的意图):
template<int dim, typename T = float>
class Vector
{
public:
typedef Vector<dim, T> VecType;
Vector() { /**/ }
Vector(const VecType& other) { /**/ )
Vector& operator=(const VecType& other) { /**/ }
VecType operator+(const VecType& other) { /**/ }
VecType operator-(const VecType& other) { /**/ }
T operator*(const VecType& other) { /**/ }
private:
std::array<T, dim> elements;
};
template<int dim, typename T>
class Vector<2>
{
public:
T x() const { return elements[0]; }
T y() const { return elements[1]; }
};
template<int dim, typename T>
class Vector<3>
{
public:
T x() const { return elements[0]; }
T y() const { return elements[1]; }
T z() const { return elements[2]; }
};
换句话说,我希望元素的默认类型为float,并且我希望dim = 2 情况下有x() 和y() 访问器方法,以及x()、y() 和z() 用于 dim = 3 案例。我对错误消息有点困惑:
vector.h:56:10: 错误:“int dim”的声明
vector.h:6:10: 错误:阴影模板参数“int dim”
(T 相同)。
我怎样才能正确地做到这一点? (如果可能的话)
【问题讨论】:
标签: c++ templates c++11 template-specialization