C++ std::bind未绑定到库`typedef`ed函数
我试图将C++ std::bind未绑定到库`typedef`ed函数,c++,class,c++17,member-function-pointers,stdbind,C++,Class,C++17,Member Function Pointers,Stdbind,我试图将std::bind与typedefs函数的库一起使用 #include <iostream> #include <string> #include <functional> typedef void (*GDBusReturnFunction) (void* user_data); class Test { void reply(void* user_data) { std::cout << "Hell
std::bind
与typedef
s函数的库一起使用
#include <iostream>
#include <string>
#include <functional>
typedef void (*GDBusReturnFunction) (void* user_data);
class Test
{
void reply(void* user_data)
{
std::cout << "Hello" << std::endl;
return;
}
void test_reply()
{
auto reply_func = std::bind(&Test::reply, this, std::placeholders::_1);
call(reply_func);
}
void call(GDBusReturnFunction func)
{}
};
int main()
{
Test();
}
但这会返回相同的错误
我缺少什么?返回未指定的类型(即未指定类型的函数对象)
使用模板化的Test::call
函数的示例解决方案可能如下所示
#包括
#包括
课堂测试
{
公众:
//也可以选择使其具有模板功能!
//例如。
//模板
//无效回复(类型*用户数据)
无效回复(无效*用户数据)
{
std::cout为什么希望这样做?call
需要一个函数指针,而您正在传递一个由std::bind
创建的函数对象。它们是不相关的类型。函数指针将无处存储绑定参数。它是固定大小的。它不是这方面的专家,因此它可能不是重复的,但必须是c与之密切相关的是call
是否应该表示库中的函数?如果是,那么它也应该将void*user_data
作为参数。否则它不能调用func
,因为它不知道传递它的参数。你到底在做什么?整个问题的关键是函数指针不是e在C++中,我们使用模板+函数/代码>代码:STD::函数< /C>。在C中,函数通常用函数指针加上“一些东西”来表示,其中“一些东西”位于void*
后面。仅要求函数指针通常是错误的。call
应该表示库中的函数。不幸的是,它确实将void*
作为参数GDBusReturnFunction
来自库。我认为OP不能使用不同的类型。GDBusReturnFunction
和call
都来自一个库,因此我无法更改它们。我将尝试一种std::function
方法。我想我理解std::bind与std::function不同的原因
prog.cc:19:11: error: cannot convert 'std::_Bind<void (Test::*(Test*, std::_Placeholder<1>))(void*)>' to 'GDBusReturnFunction' {aka 'void (*)(void*)'}
19 | call(reply_func);
| ^~~~~~~~~~
| |
| std::_Bind<void (Test::*(Test*, std::_Placeholder<1>))(void*)>
prog.cc:22:33: note: initializing argument 1 of 'void Test::call(GDBusReturnFunction)'
22 | void call(GDBusReturnFunction func)
| ~~~~~~~~~~~~~~~~~~~~^~~~
call(&reply_func);
template< class F, class... Args >
/*unspecified*/ bind( F&& f, Args&&... args );
//^^^^^^^^^^^^
[this](auto user_data) { this->reply(user_data); }
#include <iostream>
#include <string>
class Test
{
public:
// optionally you could make it also template function!
// e.g.
// template<typename Type>
// void reply(Type* user_data)
void reply(void* user_data)
{
std::cout << "Hello" << std::endl;
}
void test_reply()
{
call([this](auto user_data) { this->reply(user_data); });
}
template<typename Callable>
void call(Callable func) const
{
int userData = 1; // some user data
func(&userData);
}
};