boost :: signals2 slot作为非静态函数成员?

时间:2012-04-03 22:20:59

标签: c++ boost non-static boost-signals2

我最近一直在玩boost::signals2用于学习目的,我想知道我是否可以将信号连接到位于课堂内的非静态插槽(就像我可以在QT)。请考虑以下事项:

class Worker {
    typedef boost::signals2::signal<void (const std::string &)> SendMessage;
public:
    typedef SendMessage::slot_type SendMessageSlotType;
    boost::signals2::connection connect(const SendMessageSlotType &slot) {
        return send_message.connect(slot);
    }
private:
    SendMessage send_message;
};

class Controller {
public:
    Controller() {
        worker.connect(&Controller::print);
    }
private:
    static void print(const std::string &message) {
        std::cout << message << std::endl;
    }

    Worker worker;
};

现在我想让Controller::print成为非静态成员。以boost::thread为例,可以使用boost::bind来实现;有什么办法可以用boost::signals2吗?

1 个答案:

答案 0 :(得分:11)

只需:

class Controller {
public:
    Controller() {
        worker.connect(boost::bind(&Controller::print, this, _1));
    }
private:
    void print(const std::string &message) {
        std::cout << message << std::endl;
    }

    Worker worker;
};