gpt4 book ai didi

boost - c++0x lambdas,不让我作为函数 ptr 传递

转载 作者:行者123 更新时间:2023-12-04 17:12:44 25 4
gpt4 key购买 nike

我目前正在用 C++0x 编写一个我相当陌生的程序。
我在对象之间设置回调并使用 lambda 来匹配类型(如 boost::bind() 的方式)

如果我调用 asio 库中的函数,例如:

 socket_.async_read_some(buffer(&(pBuf->front()), szBuffer),                                                    
[=](const boost::system::error_code &error, size_t byTrans) {
this->doneRead(callBack, pBuf, error, byTrans); });

这编译得很好,并按预期运行,从 'async_read_some' 回调 'doneRead'

所以我在自己的代码中有类似的回调:
client->asyncRead([=](string msg){this->newMsg(msg); });

这只需要一个字符串,asyncReads 原型(prototype)如下
void ClientConnection::asyncRead(void(*callBack)(string)) 

但我得到这个编译错误:

Server.cpp: In member function ‘void Server::clientAccepted(std::shared_ptr, const boost::system::error_code&)’: Server.cpp:31:3: error: no matching function for call to ‘ClientConnection::asyncRead(Server::clientAccepted(std::shared_ptr, const boost::system::error_code&)::)’ Server.cpp:31:3: note: candidate is: ClientConnection.h:16:9: note: void ClientConnection::asyncRead(void (*)(std::string)) ClientConnection.h:16:9: note: no known conversion for argument 1 from ‘Server::clientAccepted(std::shared_ptr, const boost::system::error_code&)::’ to ‘void (*)(std::string)’



如何解决这个问题?

最佳答案

您的 lambda 捕获 this含蓄地。捕获事物的 lambda 无法转换为原始函数指针。

所以你需要写asyncRead所以它直接接受 lambda 函数对象,而不是让它转换为函数指针

template<typename CallbackType>
void ClientConnection::asyncRead(CallbackType callback);

或者,如果您不想将其编写为模板,则可以使用多态函数对象包装器
void ClientConnection::asyncRead(std::function<void(string)> callBack);

我还会考虑更改回调的接口(interface),以便它通过 const 引用接受字符串(除非所有回调实现本身都希望在内部修改或保存/移动传递的字符串,这在您的情况下似乎不太可能)。

关于boost - c++0x lambdas,不让我作为函数 ptr 传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6164735/

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