jeudi 8 janvier 2015

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 like this:



#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 it corrently output:



const &
&&


However, when I change the code to use template like this:



#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 becomes:



&&
&&


What's the problem? How can I optimize for moveable temporary object when using template?


Aucun commentaire:

Enregistrer un commentaire