开发者

Binding operator new?

开发者 https://www.devze.com 2022-12-08 03:38 出处:网络
I\'d like to bind operator new (see example below). If the constructor doesn\'t have any arguments, it works fine, but if it does have arguments, I apparently have trouble getting the bind syntax corr

I'd like to bind operator new (see example below). If the constructor doesn't have any arguments, it works fine, but if it does have arguments, I apparently have trouble getting the bind syntax correct.

#include <map>

#include <boost\function.hpp>
#include <boost\lambda\lambda.hpp>
#include <boost\lambda\construct.hpp>
#include <boost\lambda\bind.hpp>


enum TypeEnum
{
    BarType,
    BazType
};

class Foo
{

};

class Bar : public Foo
{
    public:
     开发者_Go百科   Bar(int x)
        {   BarVal = x; }

    private:
        int barVal;
};

class Baz : public Foo
{
    public:
        Baz(int x)
        {   bazVal = 2 * x; }

    private:
        int bazVal;
};

class FooFactory
{
    public:
        FooFactory()
        {
            // How does this work?
            factoryMap[BarType] = boost::lambda::bind(boost::lambda::new_ptr<Bar>(_1));
            factoryMap[BazType] = boost::lambda::bind(boost::lambda::new_ptr<Baz>(_1));
        }

        Foo* getFoo(TypeEnum type, int z)
        {
            return factoryMap[type](z);
        }

    private:
        std::map<TypeEnum, boost::function<Foo* (int)>> factoryMap;
};

int main()
{   
    FooFactory fooFactory;

    Bar *newBar = static_cast<Bar*> (fooFactory.getFoo(BarType, 10));

    return 0;
}


This should do:

 factoryMap[BarType] = boost::lambda::bind(boost::lambda::new_ptr<Bar>(), boost::lambda::_1);
 factoryMap[BazType] = boost::lambda::bind(boost::lambda::new_ptr<Baz>(), boost::lambda::_1);


Why not just to write the following? I can't see any reason to use bind in your case.

factoryMap[BarType] = boost::lambda::new_ptr<Bar>();
factoryMap[BazType] = boost::lambda::new_ptr<Baz>();
0

精彩评论

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