将匿名函数(lambda)保存为函数类型变量

Saving an anonymous function (lambda) as function-typed variable

本文关键字:函数 保存 类型变量 lambda      更新时间:2023-10-16

我使用一个匿名函数(也称为lambda)作为find_if的条件。很明显,我可以为它创建一个特殊的类,但C++11说我可以为此使用一个匿名函数。然而,为了可读性和理解性,我决定将匿名函数保存在类型为函数的局部变量中。

不幸的是,我得到了错误:

no match for call to '(std::function<bool(Point*, Point*)>) (Point*&)'
note: candidate is:
note: _Res std::function<_Res(_ArgTypes ...)>::operator()(_ArgTypes ...) const [with _Res = bool; _ArgTypes = {Point*, Point*}]
note:   candidate expects 2 arguments, 1 provided

我做错了什么?所谓的候选人对我来说是希腊语。我试图将lambda直接放在find_if-invokement中,但也不起作用。

#include <vector>
#include <function>
#include <algorithm>
using std::vector;
using std::function;
using std::find_if;
Point* Path::getPoint( int x, int y )
{
   function<bool( Point*, Point* )> howToFind = [&x, &y]( Point* a, Point* b ) -> bool
    {
        if( a->getX() == x )
        {
            return true;
        }
        else if( a->getX() < b->getX() )
        {
            return true;
        }
        else
        {
            return false;
        }
    };
    vector<Point*>::iterator foundYa = find_if( this->points.begin(), this->points.end(), howToFind );
    if( foundYa == points.end() )
    {
        return nullptr;
    }
    return *foundYa;
}


cnicutar给出有用答案后,代码的更正部分。我不得不在其他地方重构我的代码,但这超出了这个问题的范围:

function<bool( Point* )> howToFind = [&x, &y]( Point * a ) -> bool
{
    if( a == nullptr )
    {
        return false;
    }
    else
    {
        if( a->getX() == x && a->getY() == y )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}; 

根据cppreference,函数必须是UnaryPredicate,即它必须采用单个参数。

template< class InputIt, class UnaryPredicate >    
InputIt find_if( InputIt first, InputIt last,
                     UnaryPredicate q );