0

我有多个源自 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’

任何想法,我应该如何实现它?

4

2 回答 2

0

文档中,传递给factory-template 的参数是您期望的指针类型。所以在你的情况下boost::factory<Aa::pointer>

于 2011-05-12T11:45:33.980 回答
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;
    };

效果很好!!!

于 2011-05-13T14:06:27.947 回答