【问题标题】:Passing a member function as a callback, boost::bind, boost::function将成员函数作为回调传递,boost::bind,boost::function
【发布时间】:2016-09-18 07:47:21
【问题描述】:

在研究使用 boost::bind 和 boost::function 将成员函数作为回调传递的可能性时,我偶然发现了一种好奇心。我在玩两个班级的模型。第一个(有机体)通过 int(void) 函数 (getAge) 公开其成员变量 (age)。第二个类(生物学家)存储一个 boost::function 作为成员(callbackFunction)并使用它来确定(takeNotes)它正在研究的动物的当前年龄(它在成员变量 m_notes 中保留年龄)。第二类的实例(steve_irwin)应该“观察”(记笔记)第一类的实例(动物)。

下面是实现 Animal 类的代码:

class Organism {
public:
    Organism(int = 1);
    void growOlder();
    int getAge(void);
    void tellAge(void);
private:
    int m_age;
};

Organism::Organism(int _age) : m_age(_age) {}

void Organism::growOlder() {
    m_age++;
}

int Organism::getAge(void) {
    return m_age;
}

void Organism::tellAge(void) {
    std::cout << "This animal is : " << m_age << " years old!";
}

而这是实现 Biologist 类的代码:

class Biologist {
public:
    void setCallback(boost::function<int(void)>);
    void takeNotes();
    void tellAge();
private:
    boost::function<int(void)> updateCallback;
    int m_notes;
};

void Biologist::setCallback(boost::function<int(void)> _f) {
    updateCallback = _f;
}

void Biologist::takeNotes() {
    m_notes = updateCallback();
}

void Biologist::tellAge() {
    std::cout << "The animal I am studying is : " << m_notes <<
        " years old! WOW!" << std::endl;
}

主循环是这样的:

Organism animal(3);
Biologist steve_irwin;

boost::function<int(void)> f = boost::bind(&Organism::getAge, animal);
steve_irwin.setCallback(f);

steve_irwin.takeNotes();
steve_irwin.tellAge();
animal.tellAge();

animal.growOlder();

steve_irwin.takeNotes();
steve_irwin.tellAge();
animal.tellAge();

我创造了一个 3 岁的动物,我告诉史蒂夫欧文看它,他一开始记笔记后正确地告诉它的年龄,但是当动物长大后,他再次告诉它的年龄,他仍然认为动物3岁。

程序的输出:

The animal I am studying is : 3 years old! WOW!
This animal is : 3 years old!
The animal I am studying is : 3 years old! WOW!
This animal is : 4 years old!

我猜我以某种方式未能通过引用将成员函数作为回调传递,但我无法确定在哪里。你能帮帮我吗?

【问题讨论】:

  • 如果你的c++版本支持boost::ref' (or 'std::ref呢?

标签: c++ boost callback boost-function


【解决方案1】:

应该是boost::function&lt;int(void)&gt; f = boost::bind(&amp;Organism::getAge, &amp;animal);,而不是boost::function&lt;int(void)&gt; f = boost::bind(&amp;Organism::getAge, animal);,因为如果您按照上述方式执行,boost::bind 会创建对象的内部副本。

boost documentation for boost::bind

【讨论】:

    猜你喜欢
    • 2011-01-01
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    • 2012-09-27
    • 2015-06-15
    • 2014-06-11
    • 1970-01-01
    相关资源
    最近更新 更多