0

I was reading about "perfect forwarding". Why does this only work with a template:

// example from justsoftwaresolutions  
void g(X&& t); // 2  
void g(X& t);  // 1  

template<typename T>    
void f(T&& t)  
{  
    g(std::forward<T>(t));   
}    


int main()  
{  
    X x;  
    f(x);   // 1  
    f(X()); // 2  
}  

What is function is generated from the template for f(x) and f(X()) ?

What does std:forward

RobF
  • 1
  • 1

1 Answers1

0

Please read this to understand how std::forward works.

Regarding your question about "Why does this only work for template". My understanding is std::forward works for both template and non-template functions. But it is not necessary to use std::forward in non-template function. For example

void f(X&& x)
{
    g(std::move(x));
}

In the code above, we are sure that x is rvalue reference. so we use std::move(x) to "relay" the rvalue reference to function g(X&& x). Of course, you can use g(std::forward(x)) to do that as well, but I think it is not likely better than std::move.

Community
  • 1
  • 1
Edmund
  • 697
  • 6
  • 17