3

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 Answers 2

12

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),...);
Sign up to request clarification or add additional context in comments.

2 Comments

See the C++ FAQ Lite for exhaustive explanation about "Pointers to member functions": parashift.com/c++-faq-lite/pointers-to-members.html
Just fix spelling "filer" -> "filter".
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.