简体   繁体   English

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

[英]What does [=] mean in C++?

I want to know what [=] does?我想知道[=]是做什么的? Here's a short example这是一个简短的例子

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

How would the code work with [] instead of [=] ?代码如何使用[]而不是[=]

I assume that我假设

std::function<T (T)>

means an function prototype which gets (T) as argument and return type T ?表示一个 function 原型,它获取(T)作为参数并返回类型T

The [=] you're referring to is part of the capture list for the lambda expression. 您所指的[=]是lambda表达式的捕获列表的一部分。 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. 这告诉C ++ lambda表达式中的代码被初始化,以便lambda获取它在创建时使用的所有局部变量的副本。 This is necessary for the lambda expression to be able to refer to factor and offset , which are local variables inside the function. 这对于lambda表达式能够引用factoroffset是必要的, factoroffset量是函数内部的局部变量。

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. 如果将[=]替换为[=] [] ,则会出现编译器错误,因为lambda表达式中的代码将不知道变量offsetfactor引用的内容。 Many compilers give good diagnostic error messages if you do this, so try it and see what happens! 如果你这样做,很多编译器会给出很好的诊断错误信息,所以试试看看会发生什么!

It's a lambda capture list. 这是一个lambda捕获列表。 Makes variables available for the lambda. 使变量可用于lambda。 You can use [=] which copies by value, or [&] which passes by reference. 您可以使用[=]按值复制,或[&]通过引用传递。

I would use comment to provide this information, but I have too low reputation.我会使用评论来提供这些信息,但我的声誉太低了。

In cpp20 using [=] is now deprecated - use [=, this] instead.在 cpp20 中使用 [=] 现已弃用 - 请改用 [=, this]。

More information here: https://isocpp.org/files/papers/p0806r2.html更多信息在这里: https://isocpp.org/files/papers/p0806r2.html

As it is stated on this website "The change does not break otherwise valid C++20 code, and the earliest revision in which a breakage from C++17 could appear is C++23."正如本网站所述,“此更改不会破坏其他有效的 C++20 代码,并且可能出现来自 C++17 的破坏的最早修订版是 C++23。”

So while using cpp20 use it like this:所以在使用 cpp20 时像这样使用它:

  • [=] → [=, this]: local variables by value, class members by reference [=] → [=, this]:局部变量按值,class个成员按引用
  • [=] → [=, *this]: everything by value [=] → [=, *this]: 一切按值
  • [&] → [&, this]: everything by reference [&] → [&, this]: 一切皆参考
  • [&] → [&, *this]: (this would be unusual) [&] → [&, *this]:(这很不寻常)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM