【问题标题】:How to pass lambda expression as parameters in C++ [duplicate]如何在 C++ 中将 lambda 表达式作为参数传递 [重复]
【发布时间】:2019-09-19 08:41:38
【问题描述】:

我在 C++ 中传递 lambda 表达式时遇到了问题,我无法通过自己搜索来解决。

    template <typename T>
    int count_if(typename linkList<T>::iterator it_start, typename linkList<T>::iterator it_end, bool (*cmp)(T) ){
        int ret = 0;
        while(it_start != it_end){
            if(cmp(*it_start)) ++ret;
            ++it_start;
        }
        return ret;
    }

这是函数不包含 lambda 表达式。 我可以用下面的句子来得到答案。

 cout << algorithm::count_if(lk.begin(),lk.end(),cmp) << endl;

lk 是我自己编写的链接列表,它支持“++”“开始”“结束”函数或运算符。

但问题是我不能在这个函数中使用 lambda 表达式

 cout << algorithm::count_if(lk.begin(),lk.end(),[](int a)->bool{return a>= 50;})

我想用这句话通过 lambda 表达式得到答案。 然后我重写了函数。

    template <typename T>
    int count_if(typename linkList<T>::iterator it_start, typename linkList<T>::iterator it_end, std::function<bool (T)> _cmp){
        int ret = 0;
        while(it_start != it_end){
            if(_cmp(*it_start)) ++ret;
            ++it_start;
        }
        return ret;
    }

但编译失败。 它显示了

   candidate template ignored: could not match 'function<bool (type-parameter-0-0)>' against '(lambda at main.cpp:24:53)'
    int count_if(typename linkList<T>::iterator it_start, typename linkList<T>::iterator it_end, std::function<bool (T)> _cmp){

我不知道该怎么做,并且对这些概念感到困惑。感谢任何建议或方法来解决问题,因为我可以使用 lambda 表达式来调用我的函数

【问题讨论】:

  • 对于第一个版本,您可以使用algorithm::count_if(lk.begin(),lk.end(), +[](int a){return a&gt;= 50;})。但不需要捕获。

标签: c++ templates lambda stl


【解决方案1】:

lambda 是与std::function 不同的类型。您可以添加另一个模板参数以允许将任何可调用的(lambda 是)作为比较器函数传递。

template <typename T, typename Predicate>
int count_if(typename linkList<T>::iterator it_start, typename linkList<T>::iterator it_end, Predicate&& cmp ){
    int ret = 0;
    while(it_start != it_end){
        if(cmp(*it_start)) ++ret;
        ++it_start;
    }
    return ret;
}

【讨论】:

    猜你喜欢
    • 2012-12-27
    • 2016-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多