从unary_function继承的谓词函子,这不是一个接受 1 个参数的函数

Predicate functor inheriting from unary_function, that isn't a function taking 1 argument

本文关键字:函数 一个 参数 这不是 function unary 继承 谓词      更新时间:2023-10-16

我有一个从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
        }
    }
}

unary_function不是多态类型,它只是一个基类,用于提供argument_typeresult_type成员类型。

你可以给你的DoStuff函数传递一个std::function<bool(ThisType)>或者你让你的DoStuff函数模板

相关文章: