I'm building a c++ framework that can be extended by adding new class
I would like to find a way for simplifying the extension of new classes.
my current code look like:
class Base {
public:
virtual void doxxx() {...}
};
class X: public Base {
public:
static bool isMe(int i) { return i == 1; }
};
class Y: public Base {
public:
static bool isMe(int i) { return i == 2; }
};
class Factory {
public:
static std::unique_ptr<Base> getObject(int i) {
if (X::isMe(i)) return std::make_unique<X>();
if (Y::isMe(i)) return std::make_unique<Y>();
throw ....
}
};
Also for every new class a new if-statement must be added.
Now I would like to find a way to rewrite my Factory class (using meta programming) that adding a new class can be done by calling an add method and the factory class looks like following pseudo code:
class Factory
{
public:
static std::unique_ptr<Base> getObject(int i) {
for X in classNames:
if (X::isMe(i)) return std::make_unique<X>();
throw ....
}
static void add() {...}
static classNames[];...
};
Factory::add(X);
Factory::add(Y);
. .
is something like that possible? Many thanks in advance