[=]在C ++中是什么意思? [英] What does [=] mean in C++?

查看:395
本文介绍了[=]在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 [=]?

我认为

std::function<T (T)>

表示一个函数原型,该原型得到(T)作为参数并返回类型 T

means an function prototype which gets (T) as argument and return type T?

推荐答案

<$ c您所指的$ c> [=] 是lambda表达式的捕获列表的一部分。这告诉C ++,lambda表达式中的代码已初始化,以便lambda可以获取创建时使用的所有局部变量的副本。为了使lambda表达式能够引用 factor offset (它们是函数内部的局部变量),这是必需的。

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.

如果将 [=] 替换为 [] ,您会遇到编译器错误,因为lambda表达式中的代码将不知道变量 offset factor 参考。如果这样做,许多编译器会给出良好的诊断错误消息,因此请尝试一下,看看会发生什么!

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!

这篇关于[=]在C ++中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆