LoadFromRegistry.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <functional>
4 #include <map>
5 #include <memory>
6 #include <string>
7 
8 class TDirectory;
9 
10 namespace ana
11 {
12  /// Mechanism for derived classes to register their LoadFrom functions
13  template <typename BaseClass>
15  {
16  public:
17  // User's function will return the user's type
18  template<class T> using FuncAny_t = std::function<std::unique_ptr<T>(TDirectory*, const std::string&)>;
19 
20  // This registry will return the base class type
22 
23  template<class T> static void Register(const std::string& tag,
25  {
26  Map()[tag] = [func](TDirectory* d, const std::string& n)
27  {
28  // Convert the user's type
29  return std::unique_ptr<BaseClass>(func(d, n).release());
30  };
31  }
32 
33  static Func_t Get(const std::string& tag)
34  {
35  auto it = Map().find(tag);
36  if(it == Map().end()) return 0;
37  return it->second;
38  }
39 
40  protected:
41  static std::map<std::string, Func_t>& Map()
42  {
43  // https://isocpp.org/wiki/faq/ctors#static-init-order
44  static auto m = new std::map<std::string, Func_t>;
45  return *m;
46  }
47  };
48 }
49 
50 // Call this in your cxx file to hook up your LoadFrom function
51 #define REGISTER_LOADFROM(tag, BASE, DERIVED) \
52  struct Register##DERIVED##LoadFrom{ \
53  Register##DERIVED##LoadFrom(){ \
54  LoadFromRegistry<BASE>::FuncAny_t<DERIVED> lf = DERIVED::LoadFrom; \
55  LoadFromRegistry<BASE>::Register(tag, lf); \
56  } \
57  } gRegister##DERIVED##LoadFrom
Cuts and Vars for the 2020 FD DiF Study.
Definition: vars.h:6
set< int >::iterator it
std::function< std::unique_ptr< T >(TDirectory *, const std::string &)> FuncAny_t
Mechanism for derived classes to register their LoadFrom functions.
static Func_t Get(const std::string &tag)
static void Register(const std::string &tag, FuncAny_t< T > func)
FuncAny_t< BaseClass > Func_t
Float_t d
Definition: plot.C:236
double func(double x, double y)
::xsd::cxx::tree::string< char, simple_type > string
Definition: Database.h:154
static std::map< std::string, Func_t > & Map()