CreatorMap.hpp 2.04 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
12
13
14
15
16
17
18
19
20
21
  /** \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
22
  {    
23
  public:
24
    using CreatorMapType = std::map< std::string, CreatorInterface<BaseClass>* >;
25
26
27
28
29
30

  public:
    /// Adds a new creator together with the given key to the map.
    static void addCreator(std::string key, CreatorInterface<BaseClass>* creator)
    {
      init();
31
      AMDIS_TEST_EXIT( !creatorMap[key],
32
33
34
35
36
        "There is already a creator for key " << key);
      creatorMap[key] = creator;
    }

    /// Creates a object of the type corresponding to key.
37
    static CreatorInterface<BaseClass>* getCreator(std::string key, std::string initFileStr)
38
39
40
    {
      init();
      
41
42
43
44
45
      auto it = creatorMap.find(key);
      if (it == creatorMap.end())
        key = "default";
      
      auto creator = creatorMap[key];
46
47
48
49
50
51
52
53
54
      AMDIS_TEST_EXIT(creator,
        "No creator for key \"" << key << "\" defined in init file for parameter \"" << initFileStr << "\"");

      return creator;
    }

  protected:
    static void init()
    {
55
      if (!initialized) {
56
        initialized = true;
57
        addDefaultCreators(Type<BaseClass>{});
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
      }
    }

  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