Search code examples
c++inheritancecompile-timestatic-assert

Is there any way to enforce in C++ (at compile-time) that a derived class defines a nested type?


For example, I have a base class Event and I want to ensure that every class derived from Event has defined an enum class Type member, so that T::Type is a valid type for any class T derived from Event.


Solution

  • Even after reading your comment I still don't understand your real goal here. BUT to asnwer the specific question you asked:

    All you have to do is use the type from the derived class and you'll get a compilation error if it doesn't exist. That's the simplest approach.

    Another straightforward method that's slightly different is to use a policy class templated on the event class:

    template <typename T>
    struct EventType;
    
    template <>
    struct EventType<A>
    {
        typedef int Type;
    };