如何捕获 Lambda 标识符
How are Lambda Identifiers Captured?
我已经发布了这个答案,其中包含代码:
template <typename T>
auto vertex_triangle(const size_t index, const vector<pair<T, T>>& polygon) {
const auto& first = index == 0U ? polygon.back() : polygon[index - 1U];
const auto& second = polygon[index];
const auto& third = index == size(polygon) - 1U ? polygon.front() : polygon[index + 1U];
return [&](auto& output){ output.push_back(first);
output.push_back(second);
output.push_back(third); };
}
我在想first
、second
和third
真的可以用作lambda标识符,如下所示:
[first = index == 0U ? polygon.back() : polygon[index - 1U],
second = polygon[index],
third = index == size(polygon) - 1U ? polygon.front() : polygon[index + 1U]](auto& output){ output.push_back(first);
output.push_back(second);
output.push_back(third); };
但我只想通过不断的引用来捕捉。如果不在标识符中指定类型,我该怎么做?
你不能1.没有地方可以将 cv 限定符放在 lambda 捕获列表中。你可以看看相关的语法:
init-capture: identifier initializer & identifier initializer
也不能在捕获列表中指定类型(请参阅上面的语法)。
但是,您可以做的是通过在名称前放置一个&
来捕获非常量引用:
[&first = index == 0U ? polygon.back() : polygon[index - 1U],
&second = polygon[index],
&third = index == size(polygon) - 1U ? polygon.front() : polygon[index + 1U]](auto& output){ output.push_back(first);
output.push_back(second);
output.push_back(third); };
或者只是坚持你的第一个片段,这也更具可读性。
1 polygon
是const
,所以在您的情况下,如果您在捕获列表中通过引用捕获它们,first
、second
和third
实际上将被const
!但如果不是,那么不,出于上述原因。
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 可组合的lambda/std::函数与std::可选
- #ifdef和未声明的标识符
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 如何将lambda作为模板类的成员函数参数
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 在 lambda 捕获中声明的变量的类型推导
- f2、f3、f4标识符未找到
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 为什么lambda在clang上崩溃而不是在gcc上崩溃
- 模板函数指针和lambda
- 两组使用lambda函数的大括号
- 使lambda不可复制/不可移动
- FLTK:按下哪个按钮 - 将数字传递给按钮的回调 (lambda)
- 尝试将lambda函数放在队列中时出现一般分配器错误(可能是与unique_ptr有关的错误)
- 将带有unique_ptr的可变 lambda 传递给 const&std::function
- 如何捕获 Lambda 标识符
- 构造函数初始值设定项列表中的 Lambda 可以使用哪些标识符