[英]C++ member-function pointer
考慮以下課程
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
是static
成員時,我才能將events_filter
作為參數傳遞給do_filter
。 但我不想讓它變得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),...);
//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.