My project uses self registering classes in two ways: the one is to implement factory pattern, which allows to iterate map of this classes, the implementation is almost completely similar to the one described in C++ how safe are self registering classes?; and the other is to separate huge switch statement into map of objects. In the latter case I have just created one base class and a set of derived classes, then I instantiated each of derived classes with static object in the source file, while constructors of classes register themself in a map.
Now I'm trying to move the logic part of my app into static library and use this library in two subprojects (I use Qt, Qt Creator and gcc). After doing so, none of the above-described classes are work unless I do an exlicitly instantiation of such classes somewhere.
So, I'm looking for any workarounds. Actually, another question is arising: was it a very bad intension to design an application in c++ using self registering techniques?
EDIT: I was asked to give an example. Here is simplified code:
// Class for storing actions
class ActionBase;
class SomeObject;
class ActionMap
{
public:
ActionMap();
static void registerAction(int n, ActionBase* action) {}
void performAction (SomeObject* object, int action) {
m_actions[action]->perform(object);
}
private:
std::map<int, ActionBase*> m_actions;
};
// Action class - action.h
#include "actionmap.h"
class SomeObject;
class ActionBase
{
public:
ActionBase(int n, ActionBase* action) {ActionMap::registerAction(n, action); }
virtual ~ActionBase() = 0;
virtual void perform(SomeObject* object) = 0;
};
template<int N>
class Action : public ActionBase
{
public:
Action() : ActionBase(N, this) {}
};
template<>
class Action<1> : public ActionBase
{
public:
Action() : ActionBase(1, this) {}
void perform(SomeObject* object)
{
// Do something
}
};
Now I can create some action object in actions source file, something like:
// action.cpp
// #include "action.h"
static Action<1> action1;
After restructuring project, I have to create action1 variable somewhere in my subproject explicitly to be enable to use it, for example in the main.cpp.
Update: it seems that Angew helped me to partially solve the second problem. I have decleared a free empty function and defined it in action.cpp. Calling it somewhere in the app forces initialization of action objects.