ModErn Text Analysis
META Enumerates Textual Applications
factory.h
Go to the documentation of this file.
1 
10 #ifndef META_UTIL_FACTORY_H_
11 #define META_UTIL_FACTORY_H_
12 
13 #include <functional>
14 #include <memory>
15 #include <unordered_map>
16 
17 namespace meta
18 {
19 namespace util
20 {
21 
26 template <class DerivedFactory, class Type, class... Arguments>
27 class factory
28 {
29  public:
33  using pointer = std::unique_ptr<Type>;
35  using factory_method = std::function<pointer(Arguments...)>;
36 
38  class exception : public std::runtime_error
39  {
40  public:
41  using std::runtime_error::runtime_error;
42  };
43 
48  inline static DerivedFactory& get()
49  {
50  static DerivedFactory factory;
51  return factory;
52  }
53 
60  template <class Function>
61  void add(const std::string& identifier, Function&& fn)
62  {
63  if (methods_.find(identifier) != methods_.end())
64  throw exception{"classifier already registered with that id"};
65  methods_.emplace(identifier, std::forward<Function>(fn));
66  }
67 
75  template <class... Args>
76  pointer create(const std::string& identifier, Args&&... args)
77  {
78  if (methods_.find(identifier) == methods_.end())
79  throw exception{"unrecognized identifier"};
80  return methods_[identifier](std::forward<Args>(args)...);
81  }
82 
83  private:
85  std::unordered_map<std::string, factory_method> methods_;
86 };
87 }
88 }
89 #endif
pointer create(const std::string &identifier, Args &&...args)
Creates a new object based on the factory method parameters.
Definition: factory.h:76
std::unique_ptr< ranker > pointer
The return type for the create method.
Definition: factory.h:33
void add(const std::string &identifier, Function &&fn)
Associates the given identifier with the given factory method.
Definition: factory.h:61
Generic factory that can be subclassed to create factories for specific types.
Definition: factory.h:27
Simple exception for factories.
Definition: factory.h:38
The ModErn Text Analysis toolkit is a suite of natural language processing, classification, information retreival, data mining, and other applications of text processing.
Definition: analyzer.h:24
CRTP base template that denotes an identifier.
Definition: identifiers.h:53
std::unordered_map< std::string, factory_method > methods_
The internal map of identifiers to factory_methods.
Definition: factory.h:85
std::function< pointer(Arguments...)> factory_method
Convenience typedef for the factory methods used to create objects.
Definition: factory.h:35