I'm trying to define a static member variable outside the class definition. It works as intended. But the static_assert
that I placed inside the class definition does not compile for some reason. Why?
The error message is:
note: 'Foo<unsigned int>::var' was not initialized with a constant expression
Commenting out the static_assert
statement lets the code compile.
The code (link):
#include <iostream>
#include <cstdint>
#include <concepts>
template < std::unsigned_integral size_type >
class Foo
{
public:
inline static const size_type var;
static_assert( var <= 20, "Error" ); // note: 'Foo<unsigned int>::var' was not
// initialized with a constant expression
};
template <>
inline constexpr std::uint32_t Foo<std::uint32_t>::var { 10 };
int main( )
{
return Foo<std::uint32_t>::var;
}
Is there a way to fix this? Or should I place the static_assert
outside the class definition and after the definition of Foo<T>::var
?
Note: I might have to mention that the reason for static_assert
being inside the class body is to avoid code duplication. Otherwise, I would have to write that static assert statement after the definition of var
for every instantiation of Foo<T>
.