C++成员函数指针

问题描述:

考虑下面的类C++成员函数指针

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) 
    { 
     ... 
    } 
}; 

我可以通过events_filter作为参数向do_filter只有当events_filterstatic构件。但我不想让它变成static。有没有办法可以将指向成员函数的指针传递给另一个函数?可能会使用boost库(如函数)左右。

谢谢。

bool (Foo::*filter_Function)(Tree* node, std::list<std::string>& arg)
会给你一个成员函数指针。您传递一个有:

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

而且与调用它:跟随你的语法

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

如果你希望能够通过任何类型的函数/仿函数,使用Boost.Function,或者如果你的编译器支持它,使用std :: function。

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

    // rest as is 
}; 

然后传递任何你想要的。一个仿函数,一个免费的功能(或静态成员函数),或者甚至Boost.Bind或std :: bind的非静态成员函数(同样,如果你的编译器支持的话):

Foo f; 
f.do_filter(boost::bind(&Foo::events_filter,&f,_1,_2),...); 
+1

请参阅C++常见问题解答精简版详细解释“指向成员函数”:http://www.parashift.com/c++-faq-lite/pointers-to-members.html – 2011-03-31 11:40:21

+0

是的,那是按预期工作。谢谢 – maverik 2011-03-31 11:47:53

+0

完美无瑕。 – 2011-03-31 11:54:10

//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