Inspired by Counting function arguments at compile time
Consider this code:
template <typename... Args>
constexpr int count(Args&&...)
{
return sizeof...(Args);
}
void foo(int value)
{
static_assert(count(value) >= 0); // OK
const int& ref = 7;
static_assert(count(ref) >= 0); // Error
}
First static_assert
works fine. Second gives an error:
<source>:12:19: error: static_assert expression is not an integral constant expression
static_assert(count(ref) >= 0);
^~~~~~~~~~~~~~~
<source>:12:25: note: initializer of 'ref' is not a constant expression
static_assert(count(ref) >= 0);
^
<source>:11:16: note: declared here
const int& ref = 7;
^
Both situations are surprising to me. Why does the first static_assert
work fine, while value
is clearly not known at compile time? Why does the second static_assert
not work, while the only fundamental difference with the first is that it is supplied with a reference, not a value?