c++ - 绑定(bind)运算符新?

标签 c++ boost bind

我想绑定(bind) operator new(见下面的例子)。如果构造函数没有任何参数,它工作正常,但如果它有参数,我显然很难正确设置绑定(bind)语法。

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

最佳答案

应该这样做:

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

关于c++ - 绑定(bind)运算符新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1514392/

相关文章:

c++ - 如何将 boost::msm 状态机的实现传播/拆分为多个文件?

c++ - 几个具有不同签名的虚拟成员函数

python - 访问绑定(bind)到事件的函数的返回值 (tkinter)

c++ - 将可变参数传递给模板函数时出现编译错误

事件创建中的javascript绑定(bind)对象

c++ - MFC 中的切换按钮

C++ map<char, static method pointer>?

c++ - 是否可以转发声明命名空间内的 typedef?

c++ - 分配运算符重载

c++ - 是否可以指定 boost::program_options 需要一个选项?