在 C++20/C++23 中将参数完美转发到 lambda 捕获的最简洁方法是什么?我的意思是在协程对象内部通过复制捕获右值并通过引用捕获左值:
struct A { int _value{0}; };
auto foo = []<typename T>(T&& a) {
return [a = std::forward<T>(a)]() mutable {
++a._value;
std::cout << a._value << "\n";
};
};
A my_a;
auto capture_as_lvalue = foo(my_a);
capture_as_lvalue(); // Prints `1`.
capture_as_lvalue(); // Prints `2`.
capture_as_lvalue(); // Prints `3`.
std::cout << my_a._value << "\n"; // Should print `3`.
auto capture_as_rvalue = foo(A{});
capture_as_rvalue(); // Prints `1`.
Run Code Online (Sandbox Code Playgroud)
这个答案似乎表明上面的内容应该有效,但是上面的程序(https://godbolt.org/z/Mz3caah5o)导致
1
2
3
0 <- should be 3
1 …Run Code Online (Sandbox Code Playgroud) 我有一个协程,我想在Jupyter笔记本中作为“后台作业”运行。我已经看到了使用线程来完成此操作的方法,但是我想知道是否还可以加入笔记本的事件循环。
例如,说我有以下课程:
import asyncio
class Counter:
def __init__(self):
self.counter = 0
async def run(self):
while True:
self.counter += 1
await asyncio.sleep(1.0)
t = Counter()
Run Code Online (Sandbox Code Playgroud)
我想执行run方法(无限循环),同时仍然可以随时检查t.counter变量。有任何想法吗?
为什么 asyncio.gather 不能与生成器表达式一起使用?
import asyncio
async def func():
await asyncio.sleep(2)
# Works
async def call3():
x = (func() for x in range(3))
await asyncio.gather(*x)
# Doesn't work
async def call3():
await asyncio.gather(func() for x in range(3))
# Works
async def call3():
await asyncio.gather(*[func() for x in range(3)])
asyncio.run(call3())
Run Code Online (Sandbox Code Playgroud)
第二个变体给出:
[...]
File "test.py", line 13, in <genexpr>
await asyncio.gather(func() for x in range(3))
RuntimeError: Task got bad yield: <coroutine object func at 0x10421dc20>
Run Code Online (Sandbox Code Playgroud)
这是预期的行为吗?