传递lambda作为参数不能正常工作

时间:2014-11-23 18:41:58

标签: c++11 lambda

我正在学习lambdas,我不明白为什么将lambda作为下面的谓词传递不起作用。

class Foo2{
public:
    bool operator()(const int& n) const {return n%2 == 0;}
};

template<typename Container, typename Predicate>
unsigned int my_count_if(const Container& c, Predicate p)
{
    unsigned int cnt = 0;
    for(const auto& x : c){
        cnt += p(x) ? 1 : 0;
        std::cout << "x = " << x << std::endl; // for debug
        std::cout << "p(x) = " << p(x) << std::endl; // for debug
    }
    return cnt;
}

bool test_func(const int& n)
{
    return n%2 == 0;
}

int main()
{
    std::vector<int> v {1,2,3,4,5,6};
    std::cout << my_count_if(v, [] (const int& n) -> bool {n%2 == 0;}); // not working
    std::cout << my_count_if(v, test_func) << std::endl; // works
    std::cout << my_count_if(v, Foo2()); // works
    return 0;
}

lambda用作谓词的行不起作用。对于x的所有值,p(x)= 248,但是具有函数对象的第二个版本确实有效。我错过了关于传递lambdas作为函数参数的事情吗?在这篇文章中(在接受的答案中)Pass lambda expression to lambda argument c++11我读到了

  

在没有捕获状态的情况下,语言允许从lambda类型转换为具有operator()的签名的函数的指针(减去此部分),因此上面的lambda&gt;可以是隐式的转换为指针

感谢您的帮助!

0 个答案:

没有答案