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&&);
After my experiment, the book seems to be making a mistake here.
source share