0

我通过将普通方法和仿函数作为参数传递,我是如何被传递成员变量卡住的。

#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) ===|

我如何传递成员函数?

4

1 回答 1

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;
    }
};
于 2013-05-20T12:10:04.913 回答