I would like to be explicit about array size restrictions on a member variable, to stop others from accidentally making silly changes. The following naive attempt will not compile:
struct Foo
{
std::array< int, 1024 > some_array;
static_assert( (some_array.size() % 256) == 0, "Size must be multiple of 256" );
//^ (clang) error: invalid use of non-static data member 'some_array'
};
Even though std::array::size
is a constexpr, I can't directly use static_assert
like that because neither the function nor my member variable is static.
The solution I came up with is to use decltype
(since I don't want to typedef the array) as follows:
static_assert( (decltype(some_array)().size() % 256) == 0, "Size must be multiple of 256" );
This looks like it's default-constructing an rvalue, which I didn't think is a constexpr.
Why does this work?
Is there a cleaner way to achieve the static assertion?