gpt4 book ai didi

c++ - 使用 mem_fun_ref() 传递用户定义的成员函数

转载 作者:行者123 更新时间:2023-11-28 07:36:43 26 4
gpt4 key购买 nike

我已经完成了将普通方法和仿函数作为参数传递的过程,但我怎么一直坚持传递成员变量。

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

如何传递成员函数?

最佳答案

需要在实例上调用成员函数

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

关于c++ - 使用 mem_fun_ref() 传递用户定义的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16649163/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com