Per*_*tto 3 c++ windows multithreading reference
我需要在线程中创建对变量的引用。当像下面的代码那样执行操作时,会出现两个错误:
C2672:'std :: invoke':找不到匹配的重载函数
C2893:无法专门化功能模板“
unknown-type std::invoke(_Callable &&,_Types &&...) noexcept(<expr>)”
如何正确编码?
#include <thread>
void foo(double a, double& b)
{
b = a;
}
int main()
{
double a = 0.0, b = 0.0;
std::thread f(foo, a, b);
f.join();
}
Run Code Online (Sandbox Code Playgroud)
这就是std::reference_wrapper它的两个创作者的功能,std::ref并且std::cref是:
std::thread f(foo, a, std::ref(b));
Run Code Online (Sandbox Code Playgroud)
std::reference_wrapper<T>是一个对象,其行为实际上类似于可重新绑定的引用:它operator T&为隐式转换定义为T&,但可以重新分配。它专门用于需要“可复制参考”的情况,例如std::bind或std::thread。
使用std::ref创建一个非const引用x,并std::cref创建一个常量引用x。
| 归档时间: |
|
| 查看次数: |
56 次 |
| 最近记录: |