iMSTK
Interactive Medical Simulation Toolkit
imstkFactory.h
1 /*
2 ** This file is part of the Interactive Medical Simulation Toolkit (iMSTK)
3 ** iMSTK is distributed under the Apache License, Version 2.0.
4 ** See accompanying NOTICE for details.
5 */
6 
7 #pragma once
8 
9 #include <functional>
10 #include <memory>
11 #include <string>
12 #include <unordered_map>
13 #include <vector>
14 
15 namespace imstk
16 {
23 template<typename T, class ... Args>
25 {
26 public:
27 
28  using BaseType = T;
29  using Creator = std::function<T(Args...)>;
30 
35  static T create(const std::string& name, Args&& ... args)
36  {
37  // at will throw if name doesn't exist in the map
38  return registry().at(name)(std::forward<Args>(args)...);
39  }
40 
44  static void add(const std::string& name, Creator c)
45  {
46  registry()[name] = std::move(c);
47  }
48 
50  static bool contains(const std::string& name)
51  {
52  return registry().find(name) != registry().cend();
53  }
54 
56  static const std::vector<std::string> getNames()
57  {
58  std::vector<std::string> result;
59  for (const auto& item : registry())
60  {
61  result.push_back(item.first);
62  }
63  return result;
64  }
65 
66 private:
67  using Registry = std::unordered_map<std::string, Creator>;
68 
70  static Registry& registry()
71  {
72  static Registry registry = {};
73  return registry;
74  }
75 };
76 
86 template<typename T, typename U, typename ... Args>
88 {
89 public:
93  SharedObjectRegistrar(std::string name)
94  {
95  static_assert(std::is_base_of<T, U>::value,
96  "U must be a subclass of T");
97  ObjectFactory<std::shared_ptr<T>, Args ...>::add(name, [](Args&& ... args) { return std::make_shared<U>(std::forward<Args>(args)...); });
98  }
99 };
100 } // namespace imstk
Generic Factory class that can take objects with constructor parameters.
Definition: imstkFactory.h:24
Compound Geometry.
static const std::vector< std::string > getNames()
Definition: imstkFactory.h:56
std::function< std::shared_ptr< DeviceManager >(Args...)> Creator
Type of the function to generate a new object.
Definition: imstkFactory.h:29
static bool contains(const std::string &name)
Definition: imstkFactory.h:50
static void add(const std::string &name, Creator c)
adds a new creation function to the factory
Definition: imstkFactory.h:44
SharedObjectRegistrar(std::string name)
The constructor can automatically register the given class in the Factory For example it can be used ...
Definition: imstkFactory.h:93
static T create(const std::string &name, Args &&... args)
tries to construct the object give name, it will forward the given paramters
Definition: imstkFactory.h:35
Templated class that can add to the object factory with objects that will be generated via std::make_...
Definition: imstkFactory.h:87