0

I have a simple function that populates an array with double values and returns the array:

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:

    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. The purpose of n_steps, where the error occurs, is to set the size of the array, arr.

How could I solve this issue?

cigien
  • 57,834
  • 11
  • 73
  • 112
scott lucas
  • 31
  • 1
  • 6
  • 1
    The problem is that the argument variable itself isn't a compile-time constant variable. What is the requirements on you using an array instead of `std::vector`? Especially considering the non-matching return type? – Some programmer dude Dec 12 '21 at 11:06

1 Answers1

2

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).

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.);
Holt
  • 36,600
  • 7
  • 92
  • 139