c++ - 模板类中的条件引用声明

标签 c++ templates c++11 alias

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

例子:

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];
};

如果您有一个公共(public)基类,那么您将获得一定数量的公共(public)功能多态性。

关于c++ - 模板类中的条件引用声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35406039/

相关文章:

c++ - 类模板显式特化也可以声明其他东西吗?

c++ - 如何检查两种类型是否来自同一个模板类

c++ - 为什么内联未命名的命名空间?

c++ - 从大括号 std::string 构造 std::string_view,clang 和 gcc 不同意 -Wconversion

C++指针对象区别

c++ - 右值引用失去了它的本质

C++ 析构函数过早地删除东西(对象、指针?)

c++ - 在 f(x) 中,可以在 f 之前计算 x 吗?

c++ - AI忽略了Connect4中的设置参数

c++ - boost 时间戳 UDP 数据包