模板中的条件引用声明 class
Conditional reference declaration in template class
在模板 class 中,如何有条件地为模板定义 属性 别名?
示例:
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];
};
如果您有一个共同的基础 class,那么您将获得一定数量的共同功能多态性。
如果你可以不用数组,你可以这样做:
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 的答案可能更合适。
在模板 class 中,如何有条件地为模板定义 属性 别名?
示例:
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];
};
如果您有一个共同的基础 class,那么您将获得一定数量的共同功能多态性。
如果你可以不用数组,你可以这样做:
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 的答案可能更合适。