1 #ifndef MSP_CORE_TYPEREGISTRY_H_
2 #define MSP_CORE_TYPEREGISTRY_H_
7 #include "noncopyable.h"
12 Associates types with keywords for invoking an action. The action must be
13 a template struct or class with operator() taking two parameters. The first
14 parameter is the keyword of the type and the second is data passed in to the
15 invoke function. The type of the data is specified as the second template
16 parameter to TypeRegistry. Note that the type is used as is; if you want to
17 pass a reference, it must be explicit in the template argument.
19 template<template<typename> class A, typename T>
20 class TypeRegistry: private NonCopyable
28 TypeBase(const std::string &kw): keyword(kw) { }
30 virtual ~TypeBase() { }
32 virtual void invoke(T) const = 0;
36 class RegisteredType: public TypeBase
41 RegisteredType(const std::string &kw): TypeBase(kw) { }
43 void invoke(T arg) const override { action(this->keyword, arg); }
46 std::map<std::string, TypeBase *> types;
51 /** Registers a type. */
53 void register_type(const std::string &);
55 /** Invokes the action for a specific type, which must have been registered
57 void invoke(const std::string &, T) const;
59 /** Invokes the action for all registered types. */
60 void invoke_all(T) const;
63 template<template<typename> class A, typename T>
64 TypeRegistry<A, T>::~TypeRegistry()
70 template<template<typename> class A, typename T>
72 void TypeRegistry<A, T>::register_type(const std::string &kw)
77 types[kw] = new RegisteredType<R>(kw);
80 template<template<typename> class A, typename T>
81 void TypeRegistry<A, T>::invoke(const std::string &kw, T arg) const
83 get_item(types, kw)->invoke(arg);
86 template<template<typename> class A, typename T>
87 void TypeRegistry<A, T>::invoke_all(T arg) const
90 kvp.second->invoke(arg);