首页 > 解决方案 > 为什么在这段代码中 S 必须是 const ?

问题描述

为什么下面的代码不能编译?它说这S必须是const主要错误之一。

template <int S>
class Array 
{
    int size;
    int items [S];

public:
Array(void) :size(S){}
};

void main()
{
    int  S= 30;
    Array <5+S> array;
}

标签: c++templates

解决方案


非类型模板参数必须是constexpr,即它们必须在编译时已知。因此,S必须声明为constexpr int


推荐阅读