绑定运算符新?

时间:2009-10-03 17:42:27

标签: c++ boost bind

我想绑定operator new(参见下面的示例)。如果构造函数没有任何参数,它可以正常工作,但如果它有参数,我显然无法正确获取绑定语法。

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

2 个答案:

答案 0 :(得分:4)

这应该做:

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

答案 1 :(得分:4)

为什么不写下面的内容呢?在您的案例中,我看不出有任何理由使用bind

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