0

I have a C++ class with a static constexpr array. I'd like to assign it equal to another class member function. Right now I have the current solution, but I feel it's pretty suboptimal, and the function is no longer scoped to the class.

static constexpr std::array<Degrees, 270> angles()
{
    std::array<Degrees, 270> angles;
    for (size_t i = 0; i < angles.size(); i++)
    {
        angles[i] = static_cast<double>(i - 90.0) * (std::numbers::pi / 180.0);
    };
    return angles;
}

class MyClass
{
    static constexpr std::array<Degrees, 270> angles = angles();
}

Is there a better approach for initialising a static constexpr class member to a function like this? Ideally I'd do this using a member function of MyClass, with the implementation defined in the .cpp instead of the header.

2
  • "equal to a function" or "equal to the result of a function call"? Commented Oct 5, 2021 at 15:13
  • 1
    And no, you can't hide implementation details of constexpr code from the public header file. Commented Oct 5, 2021 at 15:14

1 Answer 1

2

If you want your member to be constexpr, you have to put the initialization in the header file.

Regarding your initialization, you can inline the function call by exploiting a lambda like so:

class MyClass
{
    static constexpr auto angles = []
    {
        std::array<Degrees, 270> angles;
        for (size_t i = 0; i < angles.size(); i++)
        {
            angles[i] = static_cast<double>(i - 90.0) * (std::numbers::pi / 180.0);
        };
        return angles;
    }();
};
Sign up to request clarification or add additional context in comments.

2 Comments

I'd auto the type of the variable. Keeps it a bit DRYer since it must be specified in the lambda anyway.
@StoryTeller-UnslanderMonica fixed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.