C++ member-function pointer

雨燕双飞 提交于 2019-11-27 16:18:20

bool (Foo::*filter_Function)(Tree* node, std::list<std::string>& arg)
Will give you a member function pointer. You pass one with:

Foo f;
f.filter(&Foo::events_filter,...);

And invoke it with:

(this->*ff)(...); // the parenthesis around this->*ff are important

If you want to be able to pass any kind of function / functor that follows your syntax, use Boost.Function, or if your compiler supports it, use std::function.

class Foo{
  typedef boost::function<bool(Tree*,std::list<std::string>&)> filter_function;

  // rest as is
};

And then pass anything you want. A functor, a free function (or static member function) or even a non-static member function with Boost.Bind or std::bind (again, if your compiler supports it):

Foo f;
f.do_filter(boost::bind(&Foo::events_filter,&f,_1,_2),...);
//member function pointer is declared as
bool (*Foo::filter_function)(Tree* node, std::list<std::string>& arg);

//Usage

//1. using object instance!
Foo foo;
filter_function = &foo::events_filter;

(foo.*filter_function)(node, arg); //CALL : NOTE the syntax of the line!


//2. using pointer to foo

(pFoo->*filter_function)(node, arg); //CALL: using pFoo which is pointer to Foo

(this->*filter_function)(node, arg); //CALL: using this which is pointer to Foo
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!