Eric Egan
Eric Egan

Reputation: 105

Instantiating template with subclass of template

I'm trying to implement a Game Engine in C/C++ for a class project. I've decided to use the acyclic visitor pattern for sending events between the subsystems since I need to be able to be extend the set of events and subsystems outside of the engine. I would like to use templates for some parts of this since a lot of the code is the same with just different types as arguments. When creating a new event I would like to inherit from the Event class template and then instantiating it with the subclass:

// Event.h
template<typename T>
class Event {
    static_assert(std::is_base_of<Event, T>::value);
public:
    void Event::accept(EventListenerBase& el){
        if (EventListener<T>* eventListener = dynamic_cast<EventListener<T>*>(*el)){
        eventListner->accept(this);
        }
    }
};

// MyNewEvent.h 
class MyNewEvent : public Event<MyNewEvent>  {

}

Is this a viable solution?

Upvotes: 1

Views: 70

Answers (1)

nh_
nh_

Reputation: 2241

Yes it is, and there is actually a name for this pattern: Curiously recurring template pattern (or CRTP).

And btw. this is not specializing the template, but instantiating it. A specialization would be

template<>
class Event<MyNewEvent> { /* ... */ };

Upvotes: 2

Related Questions