开发者

rvalue function overloading

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(st开发者_Python百科ring &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:

std::string foo(std::string in)
{
    in.insert(0, "hello ");
    return in;
}

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 in is 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.


The whole question is why do you want to have such overloads? All these overloads specify one interface: foo(x). But x parameter may be input or input/output parameter depending on its type. It is very, very error-prone. A user shall do some additional job to make sure that its variable won't be mutated. Never do that in production code.

I would agree with such overloads:

string foo(string &&in);
string foo(const string& in);

Input parameter is never changed if it is not a temporary and, at the same time, you reuse temporary objects. It seems quite reasonable.

But, why do you want to generate a lot of such overloads? && overload is for optimization. I would say very delicate optimization. Are you sure you need it in lots of places?

Anyway, if you really want to generate C++ code, templates are not a really good choice. I would use some external tool for it. Personally, I prefer Cog.


What about following simple approach ?

string& foo (string &change)  // this accepts mutable string
{
  change = string("hello ") + change;
  return change;
}

string foo (const string &unchange)  // this accepts not mutable string
{
  return string("hello ") + unchange;
}

See it's output here.


In the same vein as @iammilind's answer, but sans duplication:

#include <iostream>
using namespace std;

string foo(const string &unchange) {
  return string("hello ") + unchange;
}

string& foo(string &change) {
  return change = foo(static_cast<const string&>(foo));
}

int main(int argc, char** argv) {
    string a = "world";
    const string b = "immutable world";
    cout << foo(a) << '\n' << foo(b) << '\n';
    cout << foo(a) << '\n' << foo(b) << '\n';
}

NB: You could also use const_cast here to add the const qualification.


If you're not worried about efficiency, you can do pass by value or pass by const reference and do a copy and be done with it.

However, if you are worried about efficiency, I don't think the pass by value suggestion in this reply is the best approach. This is because I think it results in extra copies/moves, as NRVO only seems to work with local variables, not parameters. I think the way that avoids moves/copies in C++0x is the dual overloads, as illustrated by the following code:

#include <iostream>

struct A
{
  A() : i(0) {}
  A(const A& x) : i(x.i) { std::cout << "Copy" << std::endl; }
  A(A&& x) : i(x.i) { std::cout << "Move" << std::endl; }
  void inc() { ++i; }
  int i;
};

A f1(const A& x2) { A x = x2; x.inc(); return x; }
A&& f1(A&& x) { x.inc(); return std::move(x); }

A f2(A x) { x.inc(); return std::move(x); }

int main()
{
  A x;
  std::cout << "A a1 = f1(x);" << std::endl;
  A a1 = f1(x);
  std::cout << "A a2 = f1(A());" << std::endl;
  A a2 = f1(A());
  std::cout << "A b1 = f2(x);" << std::endl;
  A b1 = f2(x);
  std::cout << "A b2 = f2(A());" << std::endl;
  A b2 = f2(A());
  std::cout << std::endl;
  std::cout << "A a3 = f1(f1(x));" << std::endl;
  A a3 = f1(f1(x));
  std::cout << "A a4 = f1(f1(A()));" << std::endl;
  A a4 = f1(f1(A()));
  std::cout << "A b3 = f2(f2(x));" << std::endl;
  A b3 = f2(f2(x));
  std::cout << "A b4 = f2(f2(A()));" << std::endl;
  A b4 = f2(f2(A()));
  std::cout << std::endl;
  std::cout << "A a5 = f1(f1(f1(x)));" << std::endl;
  A a5 = f1(f1(f1(x)));
  std::cout << "A a6 = f1(f1(f1(A())));" << std::endl;
  A a6 = f1(f1(f1(A())));
  std::cout << "A b5 = f2(f2(f2(x)));" << std::endl;
  A b5 = f2(f2(f2(x)));
  std::cout << "A b6 = f2(f2(f2(A())));" << std::endl;
  A b6 = f2(f2(f2(A())));
}

Which produces the following results:

A a1 = f1(x);
Copy
A a2 = f1(A());
Move
A b1 = f2(x);
Copy
Move
A b2 = f2(A());
Move

A a3 = f1(f1(x));
Copy
Move
A a4 = f1(f1(A()));
Move
A b3 = f2(f2(x));
Copy
Move
Move
A b4 = f2(f2(A()));
Move
Move

A a5 = f1(f1(f1(x)));
Copy
Move
A a6 = f1(f1(f1(A())));
Move
A b5 = f2(f2(f2(x)));
Copy
Move
Move
Move
A b6 = f2(f2(f2(A())));
Move
Move
Move

You might be able to do some template tricks to avoid writing multiple overloads, for example:

template <class T>
param_return_type<T&&>::type f3(T&& y, typename std::enable_if<...>::type* dummy = 0 ) 
{ 
  typedef return_t param_return_type<T&&>::type;
  return_t x = static_cast<return_t>(y);
  x.inc();
  return static_cast<return_t>(x);
}

Where param_return_type<T>::type is T when passed (const) T&, and T&& when passed T&&. std::enable_if<...> you can use if you only want this template to take particular parameters.

I wasn't sure how to write a definition of param_return_type<T>::type, as it seems there is no std::remove_lvalue_reference. If anyone knows how to, feel free to edit/add to my post.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜