https://gcc.gnu.org/bugzilla/show_bug.cgi?id=117700
Bug ID: 117700
Summary: spurious error "non-constant condition" when inside a
class member
Product: gcc
Version: 14.2.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: rdiez-2006 at rd10 dot de
Target Milestone: ---
I am getting spurious errors "non-constant condition" and "use of 'this' in a
constant expression" when retrieving the size of a fixed member array, but only
from inside class members. The same expression works fine when outside the
class member.
This is a demo:
#include <cstddef>
// This is like "sizeof(arr) / sizeof(arr[0])", but with fancy C++.
template <typename T, std::size_t N>
constexpr std::size_t ArrayElemCount ( T const (&)[N] ) noexcept
{
return N;
}
class TestClass
{
public:
int m_array[ 10 ];
void test_method ( void ) const;
};
static TestClass test_instance;
// This works when checking from outside the class.
static_assert( ArrayElemCount( test_instance.m_array ) == 10 );
void TestClass::test_method ( void ) const
{
// The traditional method still works from inside the class.
static_assert( sizeof( m_array ) / sizeof( m_array[0]) == 10 );
// But this fails when checking from inside the class.
static_assert( ArrayElemCount( m_array ) == 10 );
// The compilation errors with GCC 14.2 are:
// error: non-constant condition for static assertion
// static_assert( ArrayElemCount( m_array ) == 10 );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~
// error: use of 'this' in a constant expression
}
You can play with it here:
https://godbolt.org/z/bYds71fWW