简体   繁体   English

如何将 constexpr 作为 function 参数 c++ 传递

[英]How to pass a constexpr as a function parameter c++

I have a simple function that populates an array with double values and returns the array:我有一个简单的 function 用双值填充数组并返回数组:

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
}

I pass in n_steps which is defined in main scope as:我将在主 scope 中定义的 n_steps 传递为:

    constexpr int n_step {static_cast<int>(1 / x_step) };

I get the error:我得到错误:

    error: 'n_steps' is not a constant expression
   13 |     std::array<double, n_steps + 1> vec{};

I have tried to put n_steps + 1 in curly brackets which didn't help.我试图将 n_steps + 1 放在大括号中,但没有帮助。 The purpose of n_steps, where the error occurs, is to set the size of the array, arr.发生错误的 n_steps 的目的是设置数组的大小,arr。

How could I solve this issue?我该如何解决这个问题?

Thanks in advance!提前致谢!

You cannot use a function parameter where a compile-expression is expected, because the parameter is not constexpr , even in constexpr function (your constexpr function could also be called with non- constexpr values).您不能使用constexpr参数,其中预期是constexpr -expression,因为参数constexpr constexpr

In your case, the easiest solution is probably to use a non-type template parameter:在您的情况下,最简单的解决方案可能是使用非类型模板参数:

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;
}

And then接着

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM