在模板类中,如何有条件地为模板定义属性别名?
例:
template<class Type, unsigned int Dimensions>
class SpaceVector
{
public:
std::array<Type, Dimensions> value;
Type &x = value[0]; // only if Dimensions >0
Type &y = value[1]; // only if Dimensions >1
Type &z = value[2]; // only if Dimensions >2
};
这种有条件的声明是否可行?如果是,如何?
专门
处理前两种情况:
template<class Type>
class SpaceVector<Type, 1>
{
public:
std::array<Type, 1> value; // Perhaps no need for the array
Type &x = value[0];
};
template<class Type>
class SpaceVector<Type, 2>
{
public:
std::array<Type, 2> value;
Type &x = value[0];
Type &y = value[1];
};
如果您有一个公共基类,那么您将获得通用功能的测量多态性。
如果你可以不用数组,你可以这样做:
template<class Type, std::size_t Dimension>
class SpaceVector
{
public:
Type x;
};
template<class Type>
class SpaceVector<Type, 2> : public SpaceVector<Type,1>
{
public:
Type y;
};
template<class Type>
class SpaceVector<Type, 3> : public SpaceVector<Type,2>
{
public:
Type z;
};
如果您决定支持三个以上的元素,这将更具可扩展性,但除此之外,Bathsheba的答案可能更合适。