0

I had met problems in passing lambda expression in C++ and I can't resolve it by searching myself.

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

this is the function doesn't contain lambda expression. and I can use the sentence below to get the answer.

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

lk is a linklist I write myself and it support "++" "begin" "end" functions or operator.

but what's the problem is I can't lambda expression in this function

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

I want to use this sentence to get the answer by lambda expression. and I rewrite the function.

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

but compile failed. it shows

   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){

I don't know how to do and is confused by these concepts. Thanks for any advise or methon to resolve the problem ,for that I can use lambda expression in calling my function

许羽晟
  • 13
  • 2
  • For first version, you might use `algorithm::count_if(lk.begin(),lk.end(), +[](int a){return a>= 50;})`. but requires no captures. – Jarod42 Sep 19 '19 at 11:10

1 Answers1

4

A lambda is a different type than std::function. You can add another template parameter to allow passing anything callable (which lambdas are) as the comparator function.

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;
}
perivesta
  • 3,417
  • 1
  • 10
  • 25