3
template<int N>
constexpr bool has_char_a(const char(&s)[N])
{
    for (size_t i = 0; i < N; i++)
    {
        if (s[i] == 'a') return true;
    }

    return false;
}

template<int N>
constexpr const std::string make_string(const char(&s)[N])
{
    static_assert(has_char_a(s), "error");
    return std::string{ s, N };
}

void test()
{
    cout << has_char_a("abc") << endl;
    cout << make_string("abc") << endl;
}

The compilation fails at the line with static_assert(has_char_a<N>(s),

Error C2131 expression did not evaluate to a constant

I also tried static_assert(has_char_a<N>(s), "error");, failed as well.

What's the problem?

Edit: although this post is closed, I want to give my own elaboration of the problem.

You can debug has_char_a, it would step into the for loop, so it executes every time -- it's not a const expression. The root cause is something like this: constexpr int a = (int)(const char*)"abc";

Although "abc" is a const, but the pointer, the address of the string, will not be decide during the compilation time. So it can be a constexpr.

Zhang
  • 3,030
  • 2
  • 14
  • 31
  • 2
    Parameters to `constexpr` functions are not constant expressions. `N` is a constant expression, but `s` is not. – Nicol Bolas Dec 06 '21 at 02:30

0 Answers0