Cute Chess  0.1
classregistry.h
1 /*
2  This file is part of Cute Chess.
3 
4  Cute Chess is free software: you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation, either version 3 of the License, or
7  (at your option) any later version.
8 
9  Cute Chess is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  GNU General Public License for more details.
13 
14  You should have received a copy of the GNU General Public License
15  along with Cute Chess. If not, see <http://www.gnu.org/licenses/>.
16 */
17 
18 #ifndef CLASSREGISTRY_H
19 #define CLASSREGISTRY_H
20 
21 #include <QString>
22 #include <QMap>
23 
35 #define REGISTER_CLASS(BASE, TYPE, KEY, REGISTRY) \
36  static ClassRegistration<BASE> _class_registration_ ## TYPE(REGISTRY, &ClassRegistry<BASE>::factory<TYPE>, KEY);
37 
44 template<class T>
46 {
47  public:
49  typedef T* (*Factory)(void);
50 
55  template<class Subclass>
56  static T* factory()
57  {
58  return new Subclass;
59  }
60 
63  {
64  return m_items;
65  }
67  void add(Factory f, const QString& key)
68  {
69  m_items[key] = f;
70  }
76  T* create(const QString& key)
77  {
78  if (!m_items.contains(key))
79  return nullptr;
80 
81  return m_items[key]();
82  }
83 
84  private:
85  QMap<QString, Factory> m_items;
86 };
87 
89 template<class T>
91 {
92  public:
103  typename ClassRegistry<T>::Factory factory,
104  const QString& key)
105  {
106  registry->add(factory, key);
107  }
108 };
109 
110 #endif // CLASSREGISTRY_H
T * create(const QString &key)
Definition: classregistry.h:76
ClassRegistration(ClassRegistry< T > *registry, typename ClassRegistry< T >::Factory factory, const QString &key)
Definition: classregistry.h:102
A class for creating objects based on the class&#39; runtime name or key (a string).
Definition: classregistry.h:45
const QMap< QString, Factory > & items() const
Definition: classregistry.h:62
void add(Factory f, const QString &key)
Definition: classregistry.h:67
A class for registering a new subclass of the templated class.
Definition: classregistry.h:90
T *(* Factory)(void)
Definition: classregistry.h:49
static T * factory()
Definition: classregistry.h:56