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