简体   繁体   English

C ++成员函数指针

[英]C++ member-function pointer

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. 只有当events_filterstatic成员时,我才能将events_filter作为参数传递给do_filter But I don't want to make it static . 但我不想让它变得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. 可能正在使用boost库(如函数)左右。

Thanks. 谢谢。

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. 如果您希望能够传递遵循语法的任何类型的函数/函子,请使用Boost.Function ,或者如果您的编译器支持它,请使用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): 一个仿函数,一个自由函数(或静态成员函数),甚至是一个带有Boost.Bind或std :: bind的非静态成员函数(再次,如果你的编译器支持它):

Foo f;
f.do_filter(boost::bind(&Foo::events_filter,&f,_1,_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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM