首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++成员函数指针

C++成员函数指针
EN

Stack Overflow用户
提问于 2011-03-31 11:34:43
回答 2查看 2K关注 0票数 3

考虑下一节课

代码语言:javascript
复制
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_filterdo_filter成员时,才能将events_filter作为参数传递给static。但我不想让它成为static。我是否可以将指向成员函数的指针传递给另一个函数?可能正在使用boost库(类似函数)之类。

谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-03-31 11:35:50

bool (Foo::*filter_Function)(Tree* node, std::list<std::string>& arg)

将为您提供一个成员函数指针。你通过一个:

代码语言:javascript
复制
Foo f;
f.filter(&Foo::events_filter,...);

并以下列方式引用:

代码语言:javascript
复制
(this->*ff)(...); // the parenthesis around this->*ff are important

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

代码语言:javascript
复制
class Foo{
  typedef boost::function<bool(Tree*,std::list<std::string>&)> filter_function;

  // rest as is
};

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

代码语言:javascript
复制
Foo f;
f.do_filter(boost::bind(&Foo::events_filter,&f,_1,_2),...);
票数 12
EN

Stack Overflow用户

发布于 2011-03-31 11:39:56

代码语言:javascript
复制
//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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5499155

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档