如果你想通用接口,定义构造函数有4个参数,并专注了。在内部,仅初始化这些成员,这是有效的,这种规模的载体:
template <>
Vector<1>::Vector(int _x, int _y, int _z, int _w)
: x(_x) //1D vector has only 'x'
{
}
template <>
Vector<2>::Vector(int _x, int _y, int _z, int _w)
: x(_x)
, y(_y) //2D vector has 'x' and 'y'
{
}
等。但是这是丑陋的,迫使你你做一些事情“共同”,例如,你将持有甚至4
组件2D vector
。有解决方法(用作成员变量的模板化结构,专门针对每个大小的向量),但这非常复杂。由于不同大小的矢量实际上不同类型,我会去满级的专业化:
template<int size>
class Vector;
template<>
class Vector<1>
{
protected:
int x;
public:
Vector(int _x)
: x(_x)
{ }
//other members
};
template<>
class Vector<2>
{
protected:
int x, y;
public:
Vector(int _x, int _y)
: x(_x)
, y(_y)
{ }
//other members
};
然后你就可以使用这种方式:
Vector<1> v_1(2);
Vector<2> v_2(4, 6);
//etc...
此外,第二个解决方案将允许客户端你的矢量实例化它只为那些size
s,你明确允许。
你的类'矢量<2>'是完全无关的矢量''<3>,他们是不同类型的。对于每个模板实例化,都正在定义一个构造函数,所以你没问题。可能你想做别的事情,因为我没有看到你在任何地方使用'size'。如果是这样,请澄清问题。 – vsoftco
感谢回复我得到了我的答案。 – user3877301