【发布时间】:2018-03-13 13:45:26
【问题描述】:
请在下面找到我的代码 sn-p:
std::vector<int> idx1;
std::vector<int> idx2;
framx[0].get_idx_of(atm1,idx1);
framx[0].get_idx_of(atm2,idx2);
std::vector<bool> iniz;
const int sz1=idx1.size();
const int sz2=idx2.size();
array<array<array<double,7>,sz2>,sz1> lnmat;
请在同时使用 C++ 和 clang++ 进行编译时找出错误。
analysis.cpp:408:33: error: the value of ‘sz2’ is not usable in a constant expression
array<array<array<double,7>,sz2>,sz1> lnmat;
^~~
analysis.cpp:407:15: note: ‘sz2’ was not initialized with a constant expression
const int sz2=idx2.size();
^~~
analysis.cpp:408:36: error: the value of ‘sz2’ is not usable in a constant expression
array<array<array<double,7>,sz2>,sz1> lnmat;
^
analysis.cpp:407:15: note: ‘sz2’ was not initialized with a constant expression
const int sz2=idx2.size();
^~~
analysis.cpp:408:36: note: in template argument for type ‘long unsigned int’
array<array<array<double,7>,sz2>,sz1> lnmat;
^
analysis.cpp:408:38: error: the value of ‘sz1’ is not usable in a constant expression
array<array<array<double,7>,sz2>,sz1> lnmat;
^~~
analysis.cpp:406:15: note: ‘sz1’ was not initialized with a constant expression
const int sz1=idx1.size();
^~~
analysis.cpp:408:41: error: template argument 1 is invalid
array<array<array<double,7>,sz2>,sz1> lnmat;
^
analysis.cpp:408:41: error: the value of ‘sz1’ is not usable in a constant expression
analysis.cpp:406:15: note: ‘sz1’ was not initialized with a constant expression
const int sz1=idx1.size();
^~~
analysis.cpp:408:41: note: in template argument for type ‘long unsigned int’
array<array<array<double,7>,sz2>,sz1> lnmat;
您能否告诉我在分配变量 lnmat 时出现此错误的原因?看起来可能是数组声明没有识别常量,或者它的声明有问题。
P.S.:请不要让我回答 this 问题。
【问题讨论】:
-
您能解释一下为什么您认为链接的问题不相关吗?你明白为什么你的向量的大小在编译时通常不可用吗?
-
模板参数必须在编译时知道。
const不保证这一点,就像您对sz1和sz2的情况一样。const仅表示对象是不可变的。在 C++11 中,有constexpr来定义编译时常量。但是,您仍然无法为其分配运行时值。
标签: c++ arrays multidimensional-array constants