C++ lambda 的 Lambda :函数未被捕获

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13461538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:21:21  来源:igfitidea点击:

Lambda of a lambda : the function is not captured

c++c++11lambdastd-function

提问by Vincent

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 ?

这是什么意思以及如何解决问题?

回答by cdhowie

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

f在 lambda 内部使用参数asort(),但您没有捕获它。尝试添加f到捕获列表(更改[]为 read [&f])。

回答by wendazhou

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

您在 lambda 中有效地引用了 f,它是外部作用域中的一个变量。您应该在您的捕获列表中捕获它(最简单的可能是通过引用 [&f] 或 [&] 通过引用捕获所有内容,因为您正在立即使用它)。

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.

另一方面, std::function 在执行类型擦除时有一些开销,在您的情况下,最好引入模板类型。