我在想象以下场景: 从一个空 vector 开始,将一些整数压入其中,然后使用它的大小来声明一个内置数组。
vector<int> vec; /* default init'ed */
for(decltype(vec.size()) i = 0; i != 10; ++i){
vec.push_back(i);
}
constexpr size_t sz = vec.size();
int arr[sz] = {}; /* list init, left out elem's are 0 */
这个过程对我来说很直观(作为初学者)。但它失败并显示以下消息:
testconstexpr2.cpp:22:34: error: call to non-constexpr function ‘std::vector<_Tp, _Alloc>::size_type std::vector<_Tp, _Alloc>::size() const [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]’
testconstexpr2.cpp:23:13: error: size of array ‘arr’ is not an integral constant-expression
在使用 std::array 或动态数组分配等变通方法之前,我宁愿坚持使用内置数组。
最佳答案
这行不通,因为 vec.size()
不是 constexpr
函数,并且数组维度必须是编译时常量表达式。
在 C++1y/C++14 开发期间(未完全完成)有一个名为 std::dynarray
的提案允许你这样做,但它被放弃了,也许是将在下一个 C++1z/C++17 开发期间重新启动。
你能做的是
constexpr size_t sz = 10; /* or any other integral constant expression */
int arr[sz] = {};
关于c++ - 如何获取 constexpr 变量作为声明(内置)数组的维度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24563206/