在 C + + 中[ = ]是什么意思?

我想知道 [=]是做什么的? 这里有一个简短的例子

template <typename T>
std::function<T (T)> makeConverter(T factor, T offset) {
return [=] (T input) -> T { return (offset + input) * factor; };
}


auto milesToKm = makeConverter(1.60936, 0.0);

代码如何使用 []而不是 [=]

我想是的

std::function<T (T)>

是指以 (T)作为参数并返回 T类型的函数原型?

22522 次浏览

The [=] you're referring to is part of the capture list for the lambda expression. This tells C++ that the code inside the lambda expression is initialized so that the lambda gets a copy of all the local variables it uses when it's created. This is necessary for the lambda expression to be able to refer to factor and offset, which are local variables inside the function.

If you replace the [=] with [], you'll get a compiler error because the code inside the lambda expression won't know what the variables offset and factor refer to. Many compilers give good diagnostic error messages if you do this, so try it and see what happens!

It's a lambda capture list. Makes variables available for the lambda. You can use [=] which copies by value, or [&] which passes by reference.