(1) I've this code snippet:
void tByRef(int& i) {
++i;
}
int main() {
int i = 0;
tByRef(i); // ok
thread t1(tByRef, i); // fail to compile
thread t2(tByRef, (int&)i); // fail to compile
thread t3(tByRef, ref(i)); // ok
return 0;
}
As you could see, function tByRef
accepts a lvalue reference as parameter to change the i
value. So calling it directly tByRef(i)
passes compilation.
But when I try to do same thing for thread function call, e.g. thread t1(tByRef, i)
, it fails to compile. Only when I added ref()
around i
, then it gets compiled.
Why need extra ref
call here? If this is required for passing by reference, then how to explain that tByRef(i)
gets compiled?
(2) I then changed tByRef to be template
function with &&
parameter, this time, even t3
fails to compile:
template<typename T>
void tByRef(T&& i) {
++i;
}
This &&
in template parameter type is said to be reference collapse which could accept both lvalue and rvalue reference. Why in my sample code, t1, t2, t3 all fails to compile to match it?
Thanks.