C++成员函数指针

mav*_*rik 3 c++ static-members

考虑以下课程

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)
    {
        ...
    }
};
Run Code Online (Sandbox Code Playgroud)

我可以events_filter作为参数传递给do_filter唯一events_filter的static成员.但我不想成功static.有没有办法可以将指向成员函数的指针传递给另一个函数?可能正在使用boost库(如函数)左右.

谢谢.

Xeo*_*Xeo 12

bool (Foo::*filter_Function)(Tree* node, std::list<std::string>& arg)
会给你一个成员函数指针.你通过一个:

Foo f;
f.filter(&Foo::events_filter,...);
Run Code Online (Sandbox Code Playgroud)

并调用它:

(this->*ff)(...); // the parenthesis around this->*ff are important
Run Code Online (Sandbox Code Playgroud)

如果您希望能够传递遵循语法的任何类型的函数/函子,请使用Boost.Function,或者如果您的编译器支持它,请使用std :: function.

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

  // rest as is
};
Run Code Online (Sandbox Code Playgroud)

然后传递你想要的任何东西.一个仿函数,一个自由函数(或静态成员函数),甚至是一个带有Boost.Bind或std :: bind 的非静态成员函数(再次,如果你的编译器支持它):

Foo f;
f.do_filter(boost::bind(&Foo::events_filter,&f,_1,_2),...);
Run Code Online (Sandbox Code Playgroud)