Domanda

i got through with passing normal methods and functors as arguments, how ever i got stuck with passing member variables.

#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;
}

i get this errors:

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

how do i pass a member function?

È stato utile?

Soluzione

You need to invoke the member function on an instance

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

or make it static:

class stamp  //:virtual public unary_function<const int,bool>
{
public:
    static bool stmp(const int vl) const
    {
       return false;
    }
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top