模板类中的条件引用声明

Adr*_*ire 7 c++ alias templates c++11

在模板类中,如何有条件地为模板定义属性别名?

例:

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
};
Run Code Online (Sandbox Code Playgroud)

这个有条件的声明可能吗?如果有,怎么样?

Bat*_*eba 7

专门研究前两种情况:

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];
};
Run Code Online (Sandbox Code Playgroud)

如果您有一个共同的基类,那么您将获得一定量的多态性以用于常见功能.