受到Johannes Schaub 回答的启发,我尝试实现一个反射工厂。这个想法是,您可以通过将类的名称传递给在堆上创建相关对象并返回指向公共基类的指针的方法来创建对象。如有必要,可以使用 dynamic_cast 和 RTTI 将对象转换回其原始类型。应该可以使用下图的反射工厂:
// Base is the base class of all objects to create.
class Factory: public AbstractFactory<Base>
{
public:
Factory()
{
m_map["DerivedA"] = &AbstractFactory::createInstance<DerivedA>;
m_map["DerivedB"] = &AbstractFactory::createInstance<DerivedB>;
}
};
int main()
{
Factory factory;
Base *a = factory.Create("DerivedA");
DerivedA *aa = dynamic_cast<DerivedA*>(a);
// etc..
}
到目前为止,我已经完成了这项工作。但是,下面的代码有两个主要问题。它很丑陋,如果我让抽象工厂的方法受到保护,它会抱怨它无法访问该createInstance()
方法。这是我不明白的。根据定义,派生类应该能够访问基类的受保护方法。我在 VS 2008 中测试了代码。进一步说明:我知道基类并不是真正抽象的,因为它不包含纯虚函数。我知道 std::function 但是到目前为止我还没有使用它。也许我将来会做。
#include <iostream>
#include <map>
#include <typeinfo>
#include <string>
struct Base
{
virtual std::string SayHello() = 0;
};
struct DerivedA: public Base
{
virtual std::string SayHello()
{
return "Hello from DerivedA";
}
};
struct DerivedB: public Base
{
virtual std::string SayHello()
{
return "Hello form DerivedB";
}
};
/**
* @brief Reflective Factory class. Creates objects of classes which derive from
* a common base class.
*
*/
template<class BASE_T>
struct AbstractFactory
{
// Macro to call ptrs to member functions as recommended in the C++ FAQ lite.
// http://www.parashift.com/c++-faq-lite/pointers-to-members.html
#define CALL_MEMBER_FN(object, ptrToMember) ((object).*(ptrToMember))
// Recall funcion ptr syntax for members: ReturnType (class::*) (Arguments)
// using a typedef makes it easier..
typedef BASE_T* (AbstractFactory::*func_ptr_type) ();
// retType^ ClassName^ AliasName^ Arguments^
typedef std::map<std::string, func_ptr_type> map_type;
template<typename DERIVED_T>
BASE_T * createInstance()
{ return new DERIVED_T; }
map_type m_map;
/**
* @brief Creates an object from a class with the name given as string.
*/
BASE_T * Create(std::string className)
{
// Note the last () at the end.
return CALL_MEMBER_FN(*this, m_map[className])();
}
#undef CALL_MEMBER_FN
};
class Factory: public AbstractFactory<Base>
{
public:
Factory()
{
m_map["DerivedA"] = &AbstractFactory::createInstance<DerivedA>;
m_map["DerivedB"] = &AbstractFactory::createInstance<DerivedB>;
}
};
int main()
{
Factory factory;
Base *a = factory.Create("DerivedA");
DerivedA *aa = dynamic_cast<DerivedA*>(a);
std::cout << typeid(a).name() << std::endl;
std::cout << typeid(*a).name() << std::endl;
std::cout << typeid(aa).name() << std::endl;
std::cout << aa->SayHello() << std::endl;
std::cin.get();
return 0;
}
更新
我使用 VS 2008 得到的确切错误是(在德语中,抱歉不是我的选择..)
1>------ Erstellen gestartet: Projekt: ReflectiveFactory, Konfiguration: Debug Win32 ------
1>Kompilieren...
1>main.cpp
1>.\main.cpp(82) : error C2248: "AbstractFactory<BASE_T>::createInstance": Kein Zugriff auf protected Member, dessen Deklaration in der AbstractFactory<BASE_T>-Klasse erfolgte.
1> with
1> [
1> BASE_T=Base
1> ]
1> .\main.cpp(55): Siehe Deklaration von 'AbstractFactory<BASE_T>::createInstance'
1> with
1> [
1> BASE_T=Base
1> ]
1>.\main.cpp(83) : error C2248: "AbstractFactory<BASE_T>::createInstance": Kein Zugriff auf protected Member, dessen Deklaration in der AbstractFactory<BASE_T>-Klasse erfolgte.
1> with
1> [
1> BASE_T=Base
1> ]
1> .\main.cpp(55): Siehe Deklaration von 'AbstractFactory<BASE_T>::createInstance'
1> with
1> [
1> BASE_T=Base
1> ]