<分区>
我在 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是我自己写的链表,支持“++”“begin”“end”函数或运算符。
但问题是我不能在这个函数中使用 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 表达式