I am writing a C++11 program that involves events and callbacks. I have a base class called Event, it's then derived by concrete event classes.
template <typename EventArgs>
class Event {
public:
using EventHandler = std::function<void(EventArgs)>;
void operator +=(EventHandler handlerDelegate);
void fire(EventArgs e);
private:
std::vector<EventHandler> subscribers;
};
struct TouchEventArgs { int x, int y }
struct TouchEvent : public Event<TouchEventArgs> { }
...
I was wondering if something like this was possible:
template <typename EventArgs>
using event = struct : public Event<EventName> { };
So that i could declare events like
event<TouchEventArgs> TouchEvent;
You could maintain a compile-time mapping between event types and their arg types:
namespace detail {
//primary template
template <typename EventArgs>
struct event;
//the event for TouchEventArgs is TouchEvent
template<> struct event<TouchEventArgs>
{ using type = TouchEvent; };
}
//helper template
template <typename EventArgs>
using event = typename detail::event<EventArgs>::type;
Now we can declare a variable just like you wanted (assuming the name conflict was an accident):
event<TouchEventArgs> touch_event; //decltype(TouchEvent) is TouchEvent
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.