Skip to main content
GameDev.net gamedev.net
🔒 Locked

Template and static abuse?

Started by lexs Jul 31, 2008 at 12:30 PM 5 replies 1k views
Original Post
lexs
lexs
I'm exploring abuse of templates and statics. I don't think I ever would use code like this, but what are the gotchas?

template <typename Event>
struct EventQueue
{
	static std::queue<Event *> event_queue;
};

class System
{
public:
	template <typename Event>
	void postEvent(Event * event)
	{
		EventQueue<Event>::event_queue.push(event);
	}

	template <typename Event>
	std::queue<Event *> & getEventQueue()
	{
		return EventQueue<Event>::event_queue;
	}
private:
};


Note: Untested code.
godecho
godecho
Thread safety.


Out of curiosity, why does your event queue need to be static?
lexs
lexs
Quote:
Original post by godecho
Out of curiosity, why does your event queue need to be static?


It's static so you can get only one type of events without using something like a std::string for comparison. That's the abuse :)
Antheus
Antheus
That's not really abuse, it's common with templates. It's common patter to select instances by type.

Same gotchas apply as with usual template members, this is why such approach works more reliably with stateless objects.

Quote:
It's static so you can get only one type of events without using something like a std::string for comparison.


EventQueue<MessageA> aq;EventQueue<MessageB> bq;EventQueue<MessageC> cq;


This is the way events are usually handled, so why would it be abuse?
lexs
lexs
Quote:
Original post by Antheus
This is the way events are usually handled, so why would it be abuse?


I never meant for EventQueue to be instantiated outside System, I'll code up a more complete example soon.
lexs
lexs
Something more among the lines of this:

class EventManager{public:	template <typename Event>	void subscribeToEvent(Delegate delegate)	{		EventSubscribers<Event>::subscribers.push_back(delegate);	}	template <typename Event>	void postEvent(Event * event)	{		for each subscriber in EventSubscribers<Event>::subscriber			Delegate(event);	}private:	template <typename Event>	struct EventSubscribers	{		static std::list<Delegate> subscribers;	};};


Would this cause problems with the statics if used across DLL's for example?
donny dont
donny dont
A quick gotcha with using static member variables that are or contain pointers is what happens at the end of execution. In this example if the queue still has pointers in then they will not be deleted.

Using a smart pointer of some sort will insure this doesn't happen.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.