0

I need to perform a check on a constexpr array, but can't figure out how to pass the array into the check function.

#include <cstdlib>

constexpr int is[2] = {23, 42};

void inline check(const int (&elems)[2])
{
    static_assert(elems[0] == 23, "Does not work");
}


void bar()
{
    static_assert (is[0] == 23, "Works");
    check(is);
}

Is there a way to pass the array into the check function without loosing the constexpr property?

2
  • Pass it as a template parameter. Commented May 7, 2019 at 9:36
  • You can't even do it like this with a regular int. consteval might be another solution in a year or so. Commented May 7, 2019 at 9:37

1 Answer 1

3

static_assert inside check depends on function parameter. It doesn't meter that you have pass constexpr argument to that function. Note that function are usually used multiple times. So in one case static_assert could be failing in other could passing. Static assert doesn't check from where function containing it was called. It must be verifiable during compilation without inspecting what is below.

Probably you need something like this:

constexpr int is[2] = {23, 42};

template<typename T>
constexpr bool firstElementIs23(const T& v)
{
    return v[0] == 23;
}

void bar()
{
    static_assert (firstElementIs23(is), "Works");
}

Live sample

Sign up to request clarification or add additional context in comments.

1 Comment

Introducing T is a distraction but your answer is correct good job

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.