CreatorMap.hpp 2.17 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
      test_exit(!creatorMap[key], "There is already a creator for key ", key);
39
40
41
42
      creatorMap[key] = creator;
    }

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

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

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

      return creator;
    }

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

  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