I want to overload a function so that it manipulates its argument in some way and then returns a reference to the argument – but if the argument is not mutable, then it should return a manipulated copy of the argument instead.
After messing around with it for ages, here’s what I’ve come up with.
using namespace std;
string& foo(string &in)
{
in.insert(0, "hello ");
return in;
}
string foo(string &&in)
{
return move(foo(in));
}
string foo(const string& in)
{
return foo(string(in));
}
This code seem to work correctly, but I’m interested to hear if anyone can think of a better way to do it.
Here’s a test program:
int main(void)
{
string var = "world";
const string var2 = "const world";
cout << foo(var) << endl;
cout << var << endl;
cout << foo(var2) << endl;
cout << var2 << endl;
cout << foo(var + " and " + var2) << endl;
return 0;
}
The correct output is
hello world
hello world
hello const world
const world
hello hello world and const world
I figure it would be slightly neater if I could do this:
string& foo(string &in)
{
in.insert(0, "hello ");
return in;
}
string foo(string in)
{
return move(foo(in));
}
Of course, that doesn’t work because most function calls to foo would be ambiguous – including the call in foo itself! But if I could somehow tell the compiler to prioritize the first one…
As I said, the code I posted works correctly. The main thing I don’t like about it is the repetitive extra code. If I had a bunch of functions like that it would become quite a mess, and most of it would be very repetitive. So as a second part to my question: can anyone think of a way to automatically generate the code for the second and third foo functions? eg
// implementation of magic_function_overload_generator
// ???
string& foo(string &in);
magic_function_overload_generator<foo>;
string& bar(string &in);
magic_function_overload_generator<bar>;
// etc
I would get rid of the references all together and just write one function that passes and returns by value:
If you pass an lvalue, the input string will be copied. If you pass an rvalue, it will be moved.
When leaving the function, named return value optimization will probably kick in, so the return is basically a no-op. If the compiler decides against that, the result will be moved (even though
inis an lvalue).The good thing about rvalue references is that you have to think less about where to put references in user code to gain efficiency. With movable types, pass-by-value is practically as efficient as it gets.