gpt4 book ai didi

c++ - 从 unary_function 继承的谓词仿函数,它不是一个接受 1 个参数的函数

转载 作者:太空宇宙 更新时间:2023-11-04 15:23:19 24 4
gpt4 key购买 nike

我有一个继承自 unary_function 的仿函数类:

template<class T>
class Matcher : public std::unary_function<T, bool>
{
private:
int m_match;

public:
Matcher(int valToMatch) : m_match(valToMatch) { };
bool operator() (T toTest)
{
return T.prop == m_match;
}
}

使用这些东西之一的函数:

void DoStuff(std::unary_function<ThisType, bool> & pred, 
vector<ThisType> & stuffToTest)
{
for(vector<ThisType>::iterator it = stuffToTest.begin();
it != stuffToTest.end(); ++it)
{
if(pred(*it)) // <<< Compiler complains here
{
// do stuff
}
}
}

原始调用函数:

Matcher myMatcher<ThisType>(n);
// have vector<ThisType> myStuff
DoStuff(myMatcher, myStuff);

据我所知,我有一个模板仿函数,我正在用它构造一个 ThisType 类型的实例,我将它传递给需要 unary_function 参数的函数,并使用 ThisType 的实例调用。

但是编译器提示说“term 的计算结果不是带有 1 个参数的函数”。

我错过了什么?

最佳答案

这是因为即使你将派生类对象传递给函数,函数参数仍然是 std::unary_function 没有成员 operator() 接受一个参数。因此错误。

我建议您将函数更改为函数模板:

template<typename F>
void DoStuff(F && pred, vector<ThisType> & stuffToTest)
{
for(auto it = stuffToTest.begin(); it != stuffToTest.end(); ++it)
{
if(pred(*it))
{
// do stuff
}
}
}

关于c++ - 从 unary_function 继承的谓词仿函数,它不是一个接受 1 个参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14261949/

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