While looking at the reference pages for std::forward I came across something odd. The example is passing an lvalue as an rvalue reference.. but to a global function... and it compiles and runs. I tried the same thing as a member function and it fails to compile. What gives? I would expect both calls to fail without the use of std::move
or std::forward<T>
.
#include <iostream>
template <typename T>
void globalDoSomething(T &&data) {
std::cout << "We're doing it!!" << std::endl;
}
template <typename T>
class A {
public:
void doSomething(T &&data);
};
template <typename T>
void A<T>::doSomething(T &&data)
{
std::cerr << "Ah, man. I won't compile." << std::endl;
}
template class A<int>;
int main()
{
int b = 0;
globalDoSomething(b);
A<int> a;
a.doSomething(b);
return 0;
}
It's because the automatic template deduction for globalDoSomething
infers T
as int&
.
If you explicitly instantiate the template function with globalDoSomething<int>(b);
like you did for the member function of the template class, it will also fail to compile.
Conversely, if you instantiate the template class with A<int&> a;
, it will successfully compile.