CreatorMap.hpp 2.2 KB
Newer Older
1
2
3
4
5
6
#pragma once

// std c++ headers
#include <map>

// AMDiS includes
7
#include <dune/amdis/CreatorInterface.hpp>
8
9

namespace AMDiS
10
11
{
  // forward declaration.
12
13
14
15
  // All classes that need creators must specialize this class and implement
  // a static void init() method.
  template <class BaseClass>
  struct DefaultCreators;
16
17


18
19
20
21
22
23
24
25
26
27
28
  /** \ingroup Common
   * \brief
   * A CreatorMap is used to construct objects, which types depends on key words
   * determined at run time. For example the LinearSolverInterfaceMap can create the different
   * solver types depending on the solver parameter of the init file. The benefit
   * of such creator maps is, that you can extend them only by writing an creator
   * class for your own new class and give the creator together with a key word
   * to the map.
   */
  template <class BaseClass>
  class CreatorMap
29
  {
30
  public:
31
    using CreatorMapType = std::map< std::string, CreatorInterface<BaseClass>* >;
32
33
34
35
36
37

  public:
    /// Adds a new creator together with the given key to the map.
    static void addCreator(std::string key, CreatorInterface<BaseClass>* creator)
    {
      init();
38
39
      test_exit(!creatorMap[key],
                "There is already a creator for key ", key);
40
41
42
43
      creatorMap[key] = creator;
    }

    /// Creates a object of the type corresponding to key.
44
    static CreatorInterface<BaseClass>* getCreator(std::string key, std::string initFileStr)
45
46
    {
      init();
47

48
49
50
      auto it = creatorMap.find(key);
      if (it == creatorMap.end())
        key = "default";
51

52
      auto creator = creatorMap[key];
53
54
      test_exit(creator,
                "No creator for key \"", key, "\" defined in init file for parameter \"", initFileStr, "\"");
55
56
57
58
59
60
61

      return creator;
    }

  protected:
    static void init()
    {
62
      if (!initialized) {
63
        initialized = true;
64
        DefaultCreators<BaseClass>::init();
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
      }
    }

  protected:
    /// STL map containing the pairs of keys and creators.
    static CreatorMapType creatorMap;

    static bool initialized;
  };

  template <class BaseClass>
  typename CreatorMap<BaseClass>::CreatorMapType CreatorMap<BaseClass>::creatorMap;

  template <class BaseClass>
  bool CreatorMap<BaseClass>::initialized = false;

} // end namespace AMDiS