【发布时间】:2022-01-16 05:35:51
【问题描述】:
我有一个简单的函数,它用双精度值填充数组并返回数组:
double create_step_vectors(int n_steps, double step_size)
{
std::array<double, n_steps + 1> vec{};
for (int i = 0; i <= n_steps; i++)
{
arr[i] = i * step_size;
}
return arr
}
我传入 n_steps ,它在主范围中定义为:
constexpr int n_step {static_cast<int>(1 / x_step) };
我得到错误:
error: 'n_steps' is not a constant expression
13 | std::array<double, n_steps + 1> vec{};
我尝试将 n_steps + 1 放在大括号中,但没有帮助。发生错误的n_steps的目的是设置数组的大小arr。
我该如何解决这个问题?
【问题讨论】:
-
问题是参数变量本身不是编译时常量变量。使用数组而不是
std::vector对您有什么要求?特别是考虑到不匹配的返回类型?
标签: c++ arrays function constexpr