Lambda of a lambda : the function is not captured

帅比萌擦擦* 提交于 2020-03-17 05:34:50

问题


The following program do not compile :

#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
#include <cstdlib>
#include <cmath>

void asort(std::vector<double>& v, std::function<bool(double, double)> f)
{
    std::sort(v.begin(), v.end(), [](double a, double b){return f(std::abs(a), std::abs(b));});
}

int main()
{
    std::vector<double> v({1.2, -1.3, 4.5, 2.3, -10.2, -3.4});
    for (unsigned int i = 0; i < v.size(); ++i) {
        std::cout<<v[i]<<" ";
    }
    std::cout<<std::endl;
    asort(v, [](double a, double b){return a < b;});
    for (unsigned int i = 0; i < v.size(); ++i) {
        std::cout<<v[i]<<" ";
    }
    std::cout<<std::endl;
    return 0;
}

because :

error : 'f' is not captured

What does it mean and how to solve the problem ?


回答1:


You use the f parameter in the lambda inside asort(), but you don't capture it. Try adding f to the capture list (change [] to read [&f]).




回答2:


You are effectively referencing f, which is a variable in the outer scope, in your lambda. You should capture it in your capture list (simplest is probably by reference [&f], or [&] to capture everything by reference, as you are using it immediately).

On another note, std::function has some overhead as it performs type erasure, in your case here it might be better to introduce a template type.



来源:https://stackoverflow.com/questions/13461538/lambda-of-a-lambda-the-function-is-not-captured

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!