Is there a way to convey the argument to the internal constexpr function?

advertisements

The question: is it possible to evaluate constant expression inside a function by passing (maybe with some kind of "perfect forwarding") its argument to inner constexpr function? Example:

constexpr size_t foo(char const* string_literal) {
    return /*some valid recursive black magic*/;
}

void bar(char const* string_literal) {
    // works fine
    constexpr auto a = foo("Definitely string literal.");
    // compile error: "string_literal" is not a constant expression
    constexpr auto b = foo(string_literal);
}

template<typename T>
void baz(T&& string_literal) {
    // doesn't compile as well with the same error
    constexpr auto b = foo(std::forward<T>(string_literal));
}

int main() {
    // gonna do this, wont compile due to errors mentioned above
    bar("Definitely string literal too!");
}

Can't find anything clearly prohibiting in the documentation, but the solution isn't found, as well as a proof of impossibility. Constexpr'ness of inner expression is important.


Parameters to constexpr functions cannot be assumed to be constexpr within a constexpr function; the function must work if they are not constexpr.

Type parameters can be.

If you replaced bar("hello") with bar( string_constant<'h', 'e', 'l', 'l', 'o'>{} ) with template<char...>struct string_constant{};, the value of the characters is now encoded in the type and will be available down the path. There are other ways to get the characters into a type.