我有一个派生自A
的多个类class A : public boost::enable_shared_from_this<A> {
public:
typedef boost::shared_ptr<A> pointer;
static pointer create(tcp::socket& socket) {
return pointer(new A(socket));
}
private:
A(&tcp::socket socket) : m_socket(socket) {}
tcp::socket& m_socket;
}
Class Aa : public A {
public:
typedef boost::shared_ptr<Aa> pointer;
static pointer create(tcp::socket& socket) {
return pointer(new Aa(socket));
}
private:
Aa(&tcp::socket socket) : A(socket) {}
}
Class Ab : public A {
public:
typedef boost::shared_ptr<Ab> pointer;
static pointer create(tcp::socket& socket) {
return pointer(new Ab(socket));
}
private:
Ab(&tcp::socket socket) : A(socket) {}
}
[...]
Class Ax : public A {
public:
typedef boost::shared_ptr<Ax> pointer;
static pointer create(tcp::socket& socket) {
return pointer(new Ax(socket));
}
private:
Ax(&tcp::socket socket) : A(socket) {}
}
我想使用boost :: factory创建工厂模式 我写了类似的东西:
class MyFactory {
public:
static MyFactory* getInstance();
typedef boost::function< A(tcp::socket) > a_fact;
private:
MyFactory() {
map["Aa"] = boost::bind(boost::factory< Aa::create >, _1);
map["Ab"] = boost::bind(boost::factory< Ab::create >, _1);
[…]
map["Ax"] = boost::bind(boost::factory< Ax::create >, _1);
}
std::map<std::string, a_fact> map;
};
当然,它没有编译...... 给我错误:
MyFactory.cc:13: error: type/value mismatch at argument 1 in template parameter list for ‘template<class Pointer, class Allocator, boost::factory_alloc_propagation AP> class boost::factory’
MyFactory.cc:13: error: expected a type, got ‘Aa::create’
任何想法,我应该如何实现它?
答案 0 :(得分:0)
在documentation中传递给factory
的参数 - 模板是您期望的结果的指针类型。所以在你的情况下boost::factory<Aa::pointer>
。
答案 1 :(得分:0)
如果有人犯同样的错误,请回答这里。
它不需要boost::factory
工作,直接使用boost::function
即可。
所以
class MyFactory {
public:
static MyFactory* getInstance();
typedef boost::function< A(tcp::socket) > a_fact;
private:
MyFactory() {
map["Aa"] = boost::bind(&Aa::create, _1);
map["Ab"] = boost::bind(&Ab::create, _1);
[…]
map["Ax"] = boost::bind(&Ax::create, _1);
}
std::map<std::string, a_fact> map;
};
效果很好!!!