gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:16:08 25 4
gpt4 key购买 nike

我想将一个类方法(绑定(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com