프로그래밍/C,C++
Macro 확장을 이용한 factory 만들기
MAKGA
2021. 10. 26. 22:38
320x100
특정 인터페이스 class를 상속하는 class가 있을 때,factory를 이용해서 이름으로 각각의 class instance를 생성해보자! 가 목표입니다.
#define DO_REGISTER(e) \
registry_[#e] = &templated_creator<##e>::create;
#define FACTORY_IMPL(factoryname, producttype, products) \
class factoryname \
{ \
typedef producttype* (*creator)(); \
template \
class templated_creator \
{ \
public: \
static Base_* create() { return new Derived_(); } \
}; \
public: \
factoryname() \
{ \
products(DO_REGISTER) \
} \
inline producttype* create(const std::string& name) \
{ \
auto itr = registry_.find(name); \
if (itr != registry_.end()) \
return itr->second(); \
return nullptr; \
} \
inline bool exist(const std::string& name) \
{ \
return registry_.find(name) != registry_.end(); \
} \
private: \
std::map registry_; \
}
// 다음과 같은 class가 있다고 합시다.
class Animal {};
class Dog: public Animal {};
class Cat: public Animal {};
class Rabbit: public Animal {};
//먼저 매크로 함수를 하나 만들어야 합니다.
#define ANIMAL(Func) \
Func(Dog) \
Func(Cat) \
Func(Rabbit)
//각각의 이름을 factory에 등록할 것입니다. 이제 아래와 같이 사용하면 됩니다.
FACTORY_IMPL(AnimalFactory, Animal, ANIMAL);
...
int main(int argc, char* argv)
{
AnimalFactory af;
Animal* a= af.create("Dog");
if (a) delete a;
return 0;
}
출처: https://darkblitz.tistory.com/category/Programming
320x100