C++如何将类方法传递给要求引用可调用的函数

标签 c++ c++11

我想将一个类方法(绑定(bind)到一个对象)传递给库中的一个函数,该函数要求对可调用对象进行非常量引用。

如果参数不是通过引用来询问的,它会与 std::bind 一起工作得很好。我不知道为什么它是通过引用询问的,我无法更改它。

有没有办法让 std::bind 的结果成为左值?还是我应该重做一切?

这是显示问题的代码:

#include <iostream>
#include <functional>
#include <string>
using namespace std::placeholders;

// code in a lib that i cannot change
class Agent {
public:
        template <typename functor>
        void register_handler(functor & f) {
            // f is stored in data member "functor & f_;" of connection_event_generic_dispatcher in initializer list of ctor.
            std::auto_ptr<details::connection_event_dispatcher_base> monitor(new details::connection_event_generic_dispatcher<functor>(f));

            pimpl_base_->register_connection_event_monitor(monitor);
        }
};

// code i can edit
class PersistentConnection {
public:
        PersistentConnection(): data_member_("world") {
                agent_.register_handler(std::bind(&PersistentConnection::internal_handler, this, _1));
        }

private:
        void internal_handler(std::string message) {
                std::cout << message << " " << data_member_ << std::endl;
        }

        std::string data_member_;
        Agent agent_;
};

int main (int argc, char** argv) {
        PersistentConnection p;
        return 0;
}

编译命令行及错误:

clang++ --std=c++11 /tmp/test.cpp -o /tmp/test

/tmp/test.cpp:20:10: error: no matching member function for call to 'register_handler' agent_.register_handler(std::bind(&PersistentConnection::internal_handler, this, _1)); ~~~~~~~^~~~~~~~~~~~~~~~ /tmp/test.cpp:10:7: note: candidate function [with functor = std::_Bind)> (PersistentConnection *, std::_Placeholder<1>)>] not viable: expects an l-value for 1st argument void register_handler(functor & f) { ^ 1 error generated.

最佳答案

如果 Agent 存储您传入的可调用对象并需要一个左值,而不是提供成员函数,也许您可​​以自己提供?

class PersistentConnection {
public:
    PersistentConnection(): data_member_("world") {
        agent_.register_handler(*this);
    }

    void operator()(std::srting message) {
        std::cout << message << " " << data_member_ << std::endl;
    }

    std::string data_member_;
    Agent agent_;
};

关于C++如何将类方法传递给要求引用可调用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37354058/

相关文章:

c++ - 如何正确迭代 double

基类中的 C++ 异常处理

c++ - 如何将 `std::vector` 成员变量 move 到方法的调用者?

c++ - 如何让这段涉及 unique_ptr 的代码进行编译?

c++ - 错误 : aggregate ‘food_type a’ has incomplete type and cannot be defined

c++ - 即使使用用户定义的构造函数,编译器何时仍会生成默认构造函数?

c++ - 如何强制调用类的全局实例的析构函数和构造函数(所以 "re-init"是类实例)

c++ - tbb::concurrent_queue 容器中的 std::deque 是否等效?

c++ - C++中的微线程

c++ - 在编译时找到最大公约数