Overload between rvalue reference and const lvalue reference in template

I want to overload two functions based on whether the argument is a temporary object, so I write code as follows:

#include <iostream> void f(int &&) { std::cout << "&&" << std::endl; } void f(const int&) { std::cout << "const &" << std::endl; } int main() { int i; f(i); f(i + 1); } 

And he gives out:

 const & && 

However, when I change the code to use the template as follows:

 #include <iostream> template <typename T> void f(T &&) { std::cout << "&&" << std::endl; } template <typename T> void f(const T&) { std::cout << "const &" << std::endl; } int main() { int i; f(i); f(i + 1); } 

The output will be:

 && && 

What is the problem? How to optimize a moving temporary object when using a template?

edit:

Actually, this is test code when I read C ++ Primer. It says:

 template <typename T> void f(T&&); // binds to nonconst rvalues template <typename T> void f(const T&); // lvalues and const rvalues 

After my experiment, the book seems to be making a mistake here.

+5
source share
1 answer
 template <typename T> void f(T &&) { std::cout << "&&" << std::endl; } 

Uses the universal link for forwarding and allows any type with a reverse flush.

You should use T with the missing output context, like wrapping code in a structure:

 template <typename T> struct helper { void f(T &&) { std::cout << "&&" << std::endl; } void f(const T&) { std::cout << "const &" << std::endl; } }; template <typename T> void f(T &&t) { helper<typename std::decay<T>::type>().f(std::forward<T>(t)); } 

Real time example

0
source

Source: https://habr.com/ru/post/1210643/


All Articles