Hello all, been a while, I'm working on this project for a university assignment and I would really like
delegates in C++ haha, so I came up with something in a side test project and I'm pretty sure its
evil, could someone explain to me what could happen if it is in fact evil (ignoring the usual errors that could happen)
It compiles and runs correctly in visual studio 2012 without warnings
heres the code:
#include <iostream>
#include <list>
class object
{
public:
};
struct eventargs { };
template <typename eventargs_t> struct delegate {
typedef void (object::*type)(object*, eventargs_t*);
};
typedef delegate<eventargs>::type eventhandler;
template <typename handler_t>
class event
{
private:
std::list<handler_t> _handlers;
public:
template <typename handler_u> // I would like to see if the handler_u class is derived from 'object'
void addhandler(handler_u handler) { _handlers.push_back((handler_t)handler); }
template <typename handler_u> // I would like to see if the handler_u class is derived from 'object'
void removehandler(handler_u handler) { _handlers.remove((handler_t)handler); }
void invoke(object* sender, eventargs* args)
{
std::list<handler_t>::iterator it;
for (it = _handlers.begin( ); it != _handlers.end( ); ++it)
(sender->*(*it))(sender, args);
}
};
class other : public object
{
public:
void myhandler(object* sender, eventargs* args) { std::cout << "Hello World!" << std::endl; }
void myhandler2(object* sender, eventargs* args) { std::cout << "Goodbye World!" << std::endl; }
};
int main(int, char**)
{
object *a = new other( );
event<eventhandler> e;
e.addhandler(&other::myhandler);
e.addhandler(&other::myhandler2);
e.invoke(a, nullptr);
e.removehandler(&other::myhandler);
e.invoke(a, nullptr);
return 0;
}
... Pretty sure its evil, but in what way?...
Just FYI I'm probably going to remove the templated parts of add/removehandler