2013-05-20 19 views
0

我通过传递正常的方法和函数作为参数,我怎么一直卡住传递成员变量。传递用户定义的成员函数与mem_fun_ref()

#include <iostream> 
#include <string> 
#include <vector> 
#include <functional> 
#include <algorithm> 

using namespace std; 


class stamp //:virtual public unary_function<const int,bool> 
{ 
public: 
    bool stmp(const int vl) const 
    { 
     return false; 
    } 
}; 

template<class T> 
int fncatcher(T fun) 
{ 
    fun(1); 
    return 0; 
} 

int main() 
{ 
    vector<string> names; 

    fncatcher(mem_fun_ref(&stamp::stmp));//THIS DOES NOT WORK! 

    names.push_back("GUf"); 
    names.push_back(""); 
    names.push_back("Dawg"); 
    names.push_back(""); 

    cout<<count_if(names.begin(),names.end(),mem_fun_ref(&string::empty))<<endl; //THIS WORKS 
    return 0; 
} 

我得到这个错误:

In instantiation of 'int fncatcher(T) [with T = std::const_mem_fun1_ref_t<bool, stamp, int>]':| 

required from here| 

error: no match for call to '(std::const_mem_fun1_ref_t<bool, stamp, int>) (int)'| 

note: candidate is: 

note: _Ret std::const_mem_fun1_ref_t<_Ret, _Tp, _Arg>::operator()(const _Tp&, _Arg) const [with _Ret = bool; _Tp = stamp; _Arg = int] 

note: candidate expects 2 arguments, 1 provided 

||=== Build finished: 1 errors, 2 warnings (0 minutes, 2 seconds) ===| 

我如何通过一个成员函数?

回答

1

您需要调用成员函数的一个实例

template<class T> 
int fncatcher(T fun) 
{ 
    stamp s; 
    fun(s, 1); 
    return 0; 
} 

或使其静:

class stamp //:virtual public unary_function<const int,bool> 
{ 
public: 
    static bool stmp(const int vl) const 
    { 
     return false; 
    } 
}; 
+0

既不似乎工作。 –

+1

@MauriceRodriguez:你的意思是“似乎”?它修复了编译错误吗?看我的更新 - 第一个例子是错误的。 – Eric

+0

呵呵,终于搞定了,谢谢。 –