I need to create a reference to a variable in a thread. When I do it like in the code below, I get two errors:
C2672: 'std::invoke': no matching overloaded function found
C2893: Failed to specialize function template '
unknown-type std::invoke(_Callable &&,_Types &&...) noexcept(<expr>)'
How to code it correctly?
#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();
}
That is what std::reference_wrapper and its two creator functions, std::ref and std::cref are for:
std::thread f(foo, a, std::ref(b));
[Live example]
std::reference_wrapper<T> is an object which effectively behaves like a rebindable reference: it defines operator T& for implicit conversin into T&, but can be reassigned. It is intended precisely for situations where a "copyable reference" is needed, such as std::bind or std::thread.
Use std::ref to create a non-const reference to x, and std::cref to create a const reference to x.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With