将std :: function分配给成员函数 [英] assigning std::function to a member function
本文介绍了将std :: function分配给成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class A {
public:
std::function<void(int)> f_;
void print_num(int i) {
cout << i;
}
void setFuntion(std::function<void(int)> f) {
f_=f;
}
void run() {
setFunction(print_num);
}
};
这不起作用。我得到注意:没有已知的转换从参数1从'<未解决的重载函数类型>'到'std ::函数< void(int)>'
。
this doesn't work. i get note: no known conversion for argument 1 from ‘<unresolved overloaded function type>’ to ‘std::function<void(int)>’
and other errors.
如果我把 print_num
的定义放在类外面。一切工作。我试过添加& A ::
, A ::
和 c $ c>没有帮助。
If I put the definition of print_num
outside of the class. everything works. i tried adding &A::
, A::
and this.
nothing helped.
推荐答案
print_num
静态成员函数,这意味着它具有类型 A *
的隐式第一个参数。例如,你可以通过使用lambda:
print_num
is a non-static member function, which means that it has an implicit first argument of type A*
. You can, for instance, pass that by using a lambda:
void run() {
auto myself = this;
setFunction( [myself] (int i) { myself->print_num (i); } );
}
或使用 bind
,请参阅此处
这篇关于将std :: function分配给成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文