C++成员函数指针

3
考虑以下类:
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_filterstatic 成员时,我可以将其作为参数传递给 do_filter。但是我不想将它变成 static。是否有一种方法可以将成员函数的指针传递给另一个函数?可能使用像 boost 库(如 function)之类的东西。

谢谢。

2个回答

12

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++ FAQ Lite,了解有关“成员函数指针”的详尽解释:http://www.parashift.com/c++-faq-lite/pointers-to-members.html - Julien-L
只需更正拼写错误 "filer" -> "filter"。 - Serge Dundich

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接