C++ member-function pointer

2020-01-29 18:24发布

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.

2条回答
何必那么认真
2楼-- · 2020-01-29 18:48

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),...);
查看更多
姐就是有狂的资本
3楼-- · 2020-01-29 19:03
//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
查看更多
登录 后发表回答