我有一个类树,想要将其存储在fabric中。我知道如何为具有空或预定义构造函数的元素实现fabric,但我无法看到如何使其可能绕过未预定义构造函数参数签名的情况。因此,我们可以通过以不影响工厂类的方式注册不同类型到工厂。而我们的工厂如下所示:
Factory.hpp:
因此问题是: 如何将typedef转换为
因此,我希望最终能得到以下用法示例: Example.hpp:
我的主要编译目标是最新的GCC和不幸的Visual Studio 2012,带有最新的服务包 - 因此C ++11子集相当有限但已经存在。
#include <unordered_map>
#include <string>
template<class BaseType, class BaseTypeCode>
class Factory {
public:
typedef BaseType * (*base_creator_fn)();
typedef std::unordered_map<BaseTypeCode, base_creator_fn> registry_map;
static registry_map & registry() {
static registry_map impl;
return impl;
}
static BaseType * instantiate(BaseTypeCode const & name) {
auto it = registry().find(name);
return it == registry().end() ? nullptr : (it->second)();
}
virtual ~Factory() = default;
};
template<class BaseClass, class BaseTypeCode>
struct Registrar {
Registrar(BaseTypeCode name, Factory<BaseClass>::base_creator_fn func) {
Factory<BaseClass>::registry()[name] = func;
}
};
因此问题是: 如何将typedef转换为
typedef BaseType *(* base_creator_fn)(...);
而不是当前的()
,其次如何在实例化
中转发参数,该参数将接受(BaseTypeCode const& name,...)
,最后如何从需要const数量的构造函数中获取新的base_creator_fn?因此,我希望最终能得到以下用法示例: Example.hpp:
#include "Factory.hpp"
enum ExampleTypeCode { ExampleTypeCode_Simple = 1 };
class ExampleBase {
virtual ~ExampleBase(){}
};
class Example : public ExampleBase {
Example(int i) {}
virtual ~Example(){}
static Registrar<ExampleBase, ExampleTypeCode> registrar;
};
Example.cpp:
#include <boost/bind.hpp>
#include <boost/lambda.hpp>
#include "Example.hpp"
Registrar<Example, ExampleTypeCode> Example::registrar(ExampleTypeCode_Simple, boost::bind(boost::lambda::new_ptr<Example>, _firstVarArg));
Main.cpp
#include "Example.hpp"
int main() {
ExampleBase * p = Base::instantiate(ExampleTypeCode_Simple, 1);
}
我的主要编译目标是最新的GCC和不幸的Visual Studio 2012,带有最新的服务包 - 因此C ++11子集相当有限但已经存在。
Example
并不是从ExampleBase
派生的。此外,在Example.cpp
文件中似乎有一个拼写错误。请先修复这些问题。 - Nawaz