gpt4 book ai didi

c++ - std::绑定(bind) "no matching function for call"

转载 作者:太空宇宙 更新时间:2023-11-03 10:38:13 27 4
gpt4 key购买 nike

我正在尝试为一个函数设置一个委托(delegate),并使用以下 2 个类来实现它。
底部是我收到的错误。我该如何处理?

A 级

typedef void (*SocketEventString) (String);

class SocketIO
{
public:
SocketIO();
void onMessage(SocketEventString _cb);


private:
SocketEventString _onMessage;

};

B 级

class BoardManager 
{
public:
BoardManager();
void handleAction(String action);
SocketIO io;
};

//Constructor
BoardManager::BoardManager() {

io.onMessage( std::bind( &BoardManager::handleAction, this, std::placeholders::_1 ) );
}

错误

sketch/BoardManager.cpp: In member function 'void BoardManager::initializeSocketIO()':
BoardManager.cpp:68: error: no matching function for call to 'SocketIO::onMessage(std::_Bind_helper<false, void (BoardManager::*)(String), BoardManager* const, const std::_Placeholder<1>&>::type)'
io.onMessage( std::bind( &BoardManager::handleAction, this, std::placeholders::_1 ) );
^
sketch/BoardManager.cpp:68:90: note: candidate is:
In file included from sketch/BoardManager.h:10:0,
from sketch/BoardManager.cpp:8:
sketch/SocketIO.h:25:18: note: void SocketIO::onMessage(SocketEventString)
void onMessage(SocketEventString _cb);

最佳答案

std::bind函数返回一个对象,该对象兼容或可转换为指向非成员函数的指针。

改为使用 std::function :

using SocketEventString = std::function<void(String)>;

定义

typedef void (*SocketEventString) (String);

你说 SocketEventString 是一个指向非成员函数的指针(即函数不是类或结构中的成员),它接受一个 String 类型的参数并且不返回任何值。

std::bind 函数返回未知类的对象。该对象与您定义的 SocketEventString 指针类型不同。

这两种类型(SocketEventStringstd::bind 返回的对象)不兼容。您不能从一种类型转换为另一种类型。

编译器告诉你这个,因为它试图找到一个函数 SocketIO::onMessage ,它采用 std::bind 返回的对象的类型并且不找不到任何这样的重载。

您需要使用与 std::bind 返回的对象兼容的类型,而不是您定义的 SocketEventString 类型。这就是我在上面的回答中显示的内容,将 SocketEventString 定义为不同的类型,该类型与 std::bind 返回的类型兼容。

关于c++ - std::绑定(bind) "no matching function for call",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54295219/

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