gpt4 book ai didi

c++ - 如何命名 C++ 捕获变量?

转载 作者:行者123 更新时间:2023-11-30 00:42:57 26 4
gpt4 key购买 nike

我只对通过引用将 arr 的第三个元素传递到 lambda 捕获表达式感兴趣。如果没有下面代码段中的 int &value = arr[2]; 是否可以做到这一点?

#include <functional>
#include <iostream>
#include <iterator>
#include <thread>
#include <vector>
#include <condition_variable>

int main(int argc, char *argv[])
{
std::vector<int> arr = {3,1,4};

std::cout << &arr[2] << std::endl;

std::vector<std::function<void(void)>> vfunc;
for (int i = 0; i < 3; i++) {
int a = i * 2;
int &value = arr[2];
std::function<void()> fn = [=,&value](){
//std::cout << a << std::endl;
std::cout << &value << std::endl;
};

vfunc.push_back(fn);
}

for (auto& f : vfunc)
{
f();
}

return 0;
}

最佳答案

是的,您可以通过 by-reference capture 完成它用初始化器指定。

& identifier initializer (6) (since C++14)

6) by-reference capture with an initializer

例如

std::function<void()> fn = [=,&value=arr[2]](){
// ^^^^^^^
//std::cout << a << std::endl;
std::cout << &value << std::endl;
};

关于c++ - 如何命名 C++ 捕获变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57269525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com