With rvalue references, many redundant copies may be elided, but that seems to require me to write the same function multiple times (one for an rvalue reference, one for a const
lvalue reference). But the standard library seems to only need to declare some functions once.
For example:
#include <iostream>
#include <tuple>
void foo(int&& x){
x = 2;
}
int main()
{
int x = 1;
foo(x); // compile error
std::make_tuple(x); // ok
std::cout << x << std::endl;
}
Calling foo(x)
is a compile error, because I cannot convert implicitly from int
to int&&
. But I am perplexed as to why std::make_tuple
would work. The reference says that it only accepts rvalue reference parameters. It also seems to not make copies when the value passed into it is an ravlue reference, but it would make a copy (as most would expect) when used as in my sample above.
How can I make foo
work like this?
int
,foo
needs to accept astd::string
(or some reference of it), is it good to makefoo
a template for this forwarding behaviour? Anything else not assignable to astd::string
will not make sense, and should not be passed intofoo
. – Uriel