Can I declare a constexpr
function in C++ before giving its definition?
Consider an example:
constexpr int foo(int);
constexpr int bar() { return foo(42); }
constexpr int foo(int) { return 1; }
static_assert(bar() == 1);
It is actually supported by all compilers, demo: https://gcc.godbolt.org/z/o4PThejso
But if one converts function foo
in a template:
constexpr int foo(auto);
constexpr int bar() { return foo(42); }
constexpr int foo(auto) { return 1; }
static_assert(bar() == 1);
then Clang refuses to accept it, saying https://gcc.godbolt.org/z/EG7cG9KTM:
<source>:5:15: error: static_assert expression is not an integral constant expression
static_assert(bar() == 1);
^~~~~~~~~~
<source>:2:30: note: undefined function 'foo<int>' cannot be used in a constant expression
constexpr int bar() { return foo(42); }
^
<source>:5:15: note: in call to 'bar()'
static_assert(bar() == 1);
Is it still a valid C++ code or a Clang bug?