c++ - Boost::bind 与对象占位符

标签 c++ boost boost-bind

我正在尝试实现观察者模式,但我需要在项目的后期为每个观察者添加新功能。

class Obsevers {
public:
    virtual ~Obsevers() {}
};

class TestObserver : public Obsevers {
public:
    void print1(int i) {
        std::cout << i << std::endl;
    }
};

class TestObserver2 : public Obsevers {
public:
    void print2(int i, char c) {
        std::cout << i << " , " << c << std::endl;
    }
    //possible new functions here later
};

我的通知方法如下:

template<typename Type, typename Notify>
void NotifyObserver(Notify notify) {
    typedef std::list<Obsevers*>::iterator iter;
    iter it = m_observers.begin();
    iter end = m_observers.end();
    for(; it != end; ++it) {
        Type * o = dynamic_cast<Type*>(*it);
        if(o == NULL) continue;
        notify(o);
    }
}

调用通知代码如下。

NotifyObserver<TestObserver2>(boost::bind(&TestObserver2::print2, _1, 32, 'b'));

现在给定上述代码块的上下文,我的问题是在绑定(bind)中为对象参数使用占位符 (_1) 是否正确,或者这是未定义的行为?

关于 bind 的 boost 文档没有指定仅对函数参数使用对象的占位符。

最佳答案

您的代码是正确的。

Boost.Bind文档表明您的代码

boost::bind(&TestObserver2::print2, _1, 32, 'b')

相同

boost::bind<void>(boost::mem_fn(&TestObserver2::print2), _1, 32, 'b')

哪里boost::mem_fn负责调用指向成员函数的指针。只要绑定(bind)对象被评估为 boost::mem_fn 的东西可以使用,例如指针或引用,它将正确调用该函数。

关于c++ - Boost::bind 与对象占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12590959/

相关文章:

java - 如何使 JNI RegisterNatives callack Java 函数具有 C++ 实例范围?

c++ - boost asio 套接字 : fastest way to read file from hard drive?

c++ - 将 Eigen 类型与 boost::bind 一起使用是否会自动违反 Eigen 的 "only pass by reference"规则?

objective-c - 我可以将 boost::bind() 转换为 Objective C 函数吗?

c++ - 类内中断

c++ - cin,输入所需详细信息后无输出

c++ - V8 回调,用数字代替字符串

C++ 无输出,boost.asio

c++ - 在 x64 上获取真正的 C++ 异常

c++ - 使用模板和 boost 功能