Moh*_* El 2 c++ g++ metaprogramming template-meta-programming
我正在构建一个可以通过添加新类来扩展的c ++框架
我想找到一种简化新类扩展的方法.
我目前的代码如下:
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 ....
}
};
Run Code Online (Sandbox Code Playgroud)
此外,对于每个新类,都必须添加新的if语句.
现在我想找到一种方法来重写我的Factory类(使用元编程),可以通过调用add方法来完成添加新类,并且工厂类看起来像跟随伪代码:
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);
Run Code Online (Sandbox Code Playgroud)
..
有可能吗?提前谢谢了
您可能会执行以下操作:
template <typename ... Ts>
class Factory {
public:
static std::unique_ptr<Base> createObject(int i) {
if (i < sizeof...(Ts)) {
static const std::function<std::unique_ptr<Base>()> fs[] = {
[](){ return std::make_unique<Ts>();}...
};
return fs[i]();
}
throw std::runtime_error("Invalid arg");
}
};
Run Code Online (Sandbox Code Playgroud)
用法是:
using MyFactory = Factory<X, Y /*, ...*/>;
auto x = MyFactory::createObject(0);
auto y = MyFactory::createObject(1);
Run Code Online (Sandbox Code Playgroud)
如果您想要运行时注册,则可以改为:
class Factory {
public:
static std::unique_ptr<Base> createObject(int i) {
auto it = builders.find(i);
if (it == builders.end()) {
throw std::runtime_error("Invalid arg");
}
return it->second();
}
template <typename T>
void Register()
{
builders.emplace(T::Id, [](){ return std::make_unique<T>();});
}
private:
std::map<int, std::function<std::unique_ptr<Base>()>> builders;
};
Run Code Online (Sandbox Code Playgroud)
用法是:
class X: public Base {
public:
static constexpr int id = 1;
};
class Y: public Base {
public:
static constexpr int id = 2;
};
Run Code Online (Sandbox Code Playgroud)
和
Factory factory;
factory.register<X>();
factory.register<Y>();
auto x = factory.createObject(1);
auto y = factory.createObject(Y::id);
Run Code Online (Sandbox Code Playgroud)