开发者

boost::factory creating boost::enable_shared_from_this class

I have multiple class derivated from 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) {}
}

I would like to create a factory pattern using boost::factory I have writted something like that :

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;
    };

And of course, it does not compil... giving me the error :

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:   开发者_StackOverflowexpected a type, got ‘Aa::create’

Any idea, how should I implement it ?


In the documentation the argument passed to the factory-template is the pointer type you expect as a result. So in your case boost::factory<Aa::pointer>.


If anyone goes into the same mistake, Here the answer. It does not need boost::factory to work, using boost::function directly is enough.

so

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;
    };

Works great !!!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜