我正在this example之后创建自我注册的课程:
我已经启动并运行了这个示例,但现在我发现自己遇到了需要以类似于此的方式将参数传递给派生类的构造函数的麻烦:
int* n = generateRandomInteger();
std::string attributes = readFirstLine(file);
// converts the string of attributes in a map of strings
std::map<string, string>* m = createMap(attributes);
// n and m would be parameters that the constructor would use
Base* b = BaseFactory::createInstance(object_components->Attribute("id"),n,m);
所有派生类都使用相同数量的相同数量或参数,因此我想用于创建新对象的函数模板可以使用这些固定类型。
我尝试的是:
#ifndef BFACT_H
#define BFACT_H
#include "B.h"
#include <iostream>
template<typename T>
B * createT(int* a, std::string* b)
{
return new T(a,b);
}
struct BaseFactory {
//typedef std::map<std::string, B*(*)(SDLGameObject*,std::map<string,string>*)> map_type;
typedef std::map<std::string, B*(*)(int*,std::string*)> map_type;
static B * createInstance(std::string const& s, int* a, std::string* b) {
map_type::iterator it = getMap()->find(s);
if(it == getMap()->end())
return 0;
return it->second(a,b);
}
protected:
static map_type * getMap() {
// never delete'ed. (exist until program termination)
// because we can't guarantee correct destruction order
if(!map)
{
map = new map_type;
}
return map;
}
private:
static map_type * map;
};
template<typename T>
struct DerivedRegister : BaseFactory {
DerivedRegister(std::string const& s)
{
getMap()->insert(std::make_pair(s, &createT<T>(int*, std::string*)));
}
};
#endif // BFACT_H
但我得到的错误数量太高了。