Is there a way to force derived types to define a static constexpr in C++? I have a base class, and I want to force every derived class to define a static const bool has_property.
I tried doing this with CRTP (so that each derived class gets its own static const):
template <typename T, class MyClass>
struct Base {
T data;
static constexpr bool has_property;
};
template <typename T>
struct Derived : public Base<T, Derived<T> > {
static constexpr bool has_property = false;
};
But the compiler complains that Base::has_property is not initialized.
How can I accomplish this?
We could insert a
static_assertinto the constructor ofBase:This check will only work when the derived class is instantiated, and the default constructor of
Baseis used. Theconstexprcheck doesn’t work in g++ 4.7 at the moment.Alternatively, you could use a type traits instead of a
constexprstatic member, e.g.