The following code is a simplified version of what I use for event dispatching. The essential point is that there is a static_cast<T*> on the argument of a template functor and another class makes sure that the argument passed to the functor is what the static_cast casts to.
struct AbstractArg {
virtual ~AbstractArg() { }
};
struct AbstractFunctor {
virtual void operator()(AbstractArg*) const = 0;
virtual ~AbstractFunctor() { }
};
namespace evil {
template<typename ArgT>
struct CastingFunctor : AbstractFunctor {
void operator()(AbstractArg* aarg) const
{
ArgT* arg = static_cast<ArgT*>(arg); // Danger!
// ... do stuff with it
}
};
} // namespace evil
class TypeidManager
{
public:
typedef std::map<std::string, AbstractFunctor*> map_type;
void dispatch(AbstractArg* arg) const
{
map_type::const_iterator it = typeid_map.find(std::string(typeid(*arg).name()));
if (it != typeid_map.end())
{
AbstractFunctor* pFunctor = it->second;
(*pFunctor)(arg);
}
};
template<typename ArgT>
void register_func( void (*fun_ptr)(ArgT*))
{
typeid_map.insert(std::make_pair(std::string(typeid(ArgT).name()),
new evil::CastingFunctor<ArgT>));
}
private:
map_type typeid_map;
};
Is there a name for this pattern?
Thanks!