【问题标题】:How to pass a constexpr as a function parameter c++ [duplicate]如何将constexpr作为函数参数传递c ++ [重复]
【发布时间】: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


【解决方案1】:

你不能在需要编译表达式的地方使用函数参数,因为参数不是constexpr,即使在constexpr函数中(你的constexpr函数也可以用非constexpr值调用) .

在您的情况下,最简单的解决方案可能是使用非类型模板参数:

template <int n_steps>
auto create_step_vectors(double step_size)
{
    std::array<double, n_steps + 1> arr;
    for (int i = 0; i <= n_steps; i++)
    {
        arr[i] = i * step_size;
    }
    return arr;
}

然后

constexpr int n_step{ static_cast<int>(1 / x_step) };
const auto arr = create_step_vectors<n_step>(1.);

【讨论】:

    猜你喜欢
    • 2011-04-07
    • 2015-09-28
    • 2013-08-13
    • 2020-08-03
    • 2014-10-27
    • 1970-01-01
    • 2015-11-21
    • 2017-02-12
    相关资源
    最近更新 更多