Reputation: 5586
Consider the following class
class Foo
{
typedef bool (*filter_function)(Tree* node, std::list<std::string>& arg);
void filter(int filter, std::list<std::string>& args)
{
...
if (filter & FILTER_BY_EVENTS) {
do_filter(events_filter, args, false, filter & FILTER_NEGATION);
}
...
}
void do_filter(filter_function ff, std::list<std::string>& arg,
bool mark = false, bool negation = false, Tree* root = NULL)
{
...
}
bool events_filter(Tree* node, std::list<std::string>& arg)
{
...
}
};
I can pass events_filter
as a parameter to the do_filter
only when events_filter
is static
member. But I don't want to make it static
. Is there a way in which I can pass pointer to the member-function to another function? May be using boost libraries (like function) or so.
Thanks.
Upvotes: 3
Views: 2067
Reputation: 131789
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),...);
Upvotes: 12
Reputation: 361342
//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
Upvotes: 2