나는 패브릭에 저장하려는 클래스 트리가 있습니다. 비어 있거나 미리 정의 된 생성자가있는 요소에 대해 fabric을 구현하는 방법을 볼 수 있지만 미리 정의 된 생성자 인수 시그니처를 사용하여이를 해결할 수있는 방법을 찾지 못합니다. 그래서 우리는 register diferent types into factory in a way that does not affect factory class directly라고 말하십시오. 그리고 우리 공장은 다음과 같습니다팩토리 요소 생성자에 인수를 전달하는 방법은 무엇입니까?
Factory.hpp을 :
#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 BaseType * (*base_creator_fn)(...);
에 형식 정의를 만들려면 두 번째 instantiate
에 인수를 전달하는 방법이 (BaseTypeCode const & name, ...)
을 취하고 마지막으로 const_mount 인수를 취하는 생성자에서 새 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 하위 집합은 아직 제한적입니다.
나는 당신이 일종의 지우개를 사용해야한다고 생각한다. C++ 11, BTW를 사용할 수 있습니까? – Nawaz
말하자면, 'Example'은 ExampleBase에서 파생되지 않았습니다. 또한,'Example.cpp' 파일에 오타가있는 것 같습니다. 먼저이 문제를 해결하십시오. – Nawaz
@Nswaz : 일부 오타가 수정되었습니다. VS2012의 주요 통증 ... 일부 C++ 11은 아직 거의 전부가 아닙니다. – DuckQueen