我创建了一个最小的例子来说明我的问题。
#include <iostream>
#include <memory>
#include <vector>
#include <functional>
class Bar {
public:
void bind_function(std::function<void(int)> callback){
m_callbacks.push_back(callback);
}
void invoke() {
for(auto& c : m_callbacks){
c(12345);
}
}
private:
std::vector<std::function<void(int)>> m_callbacks;
};
class Foo{
public:
void register_foo(){ m_msg.bind_function(std::bind(&Foo::callback_foo, this)); }
void callback_foo(/*int a*/){ std::cout << "callback foo invoked!!!!" << std::endl; }
void run() { m_msg.invoke(); }
private:
Bar m_msg;
};
int main(){
Foo foo;
foo.register_foo();
foo.run();
return 0;
}
我有一个
Bar
类,它有两个方法: Bar::bind_function
传递一个函数指针以被推入某个向量。还有一个 Bar::invoke
方法,它将调用向量中的回调。
然后我有一个
Foo
,它具有三个方法:一个 Foo::register_foo
方法,我将从 Bar 调用 Bar::bind_function
和要调用的实际方法 Foo::callback_foo
。
最后是Foo::run
注册函数的方法。
代码编译,我可以看到正在执行的回调/注册方法。
[问题]
如果函数指针来自这个向量,为什么代码可以编译:
std::vector<std::function<void(int)>> m_callbacks
与实际回调不符:
void callback_foo(/*int a*/){...}
一个是
void(int)
另一个是void()
.
如果我取消注释我的
void callback_foo(/*int a*/){...}
以匹配void callback_foo(int a){...}
我收到以下错误:
error: static assertion failed: Wrong number of arguments for pointer-to-member
我该如何解决这个错误?