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:
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.
Related
Is it possible to perfectly forward *this object inside member functions? If yes, then how can we do it? If no, then why not, and what alternatives do we have to achieve the same effect.
Please see the code snippet below to understand the question better.
class Experiment {
public:
double i, j;
Experiment(double p_i = 0, double p_j = 0) : i(p_i), j(p_j) {}
double sum() { return i + j + someConstant(); }
double someConstant() && { return 10; }
double someConstant() & { return 100; }
};
int main() {
Experiment E(3, 5);
std::cout << std::move(E).sum() << "\n"; // prints: 108
std::cout << E.sum() << "\n"; // prints: 108
}
This output seems expected if we consider that *this object inside the member function double sum() is always either an lvalue or xvalue (thus a glvalue) . Please confirm if this is true or not.
How can we perfectly forward *this object to the member function call someConstant() inside the double sum() member function?
I tried using std::forward as follows:
double sum() {
return i + j + std::forward<decltype(*this)>(*this).someConstant();
}
But this did not have any effect, and double someConstant() & overload is the one always being called.
This is not possible in C++11 without overloading sum for & and && qualifiers. (In which case you can determine the value category from the qualifier of the particular overload.)
*this is, just like the result of any indirection, a lvalue, and is also what an implicit member function call is called on.
This will be fixed in C++23 via introduction of an explicit object parameter for which usual forwarding can be applied: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0847r7.html
One would think that std::forward() would preserve lvalue references but it doesn't in non-template contexts, as the example below shows.
Both call_f()& and call_f()&& call f()&&. std::forward<Experiment>(*this) in a non-template function returns an rvalue reference regardless of the value category of the argument.
Note how this works differently from a template function, member or not (I made the member function static because it receives a "this reference" as an explicit parameter) . Both forward lvalue references "properly" (the last 4 calls).
#include<iostream>
#include<utility>
#include<string>
struct Experiment
{
public:
std::string f()&& { return "f()&&"; }
std::string f()& { return "f()&"; }
std::string call_f()&& { std::cout << "call_f()&& "; return std::forward<Experiment>(*this).f(); }
// I need this function because it is not a template function
std::string call_f()& { std::cout << "call_f()& "; return std::forward<Experiment>(*this).f(); }
template<class T = Experiment>
static std::string E_t_call_f(T&& t) { std::cout << "E_t_call_f(T&& t) "; return std::forward<T>(t).f(); }
};
template<class T>
std::string t_call_f(T&& t) { std::cout << "t_call_f(T&& t) "; return std::forward<T>(t).f(); }
int main()
{
Experiment E;
std::cout << "E.f(): " << E.f() << '\n';
std::cout << "move(E).f(): " << std::move(E).f() << '\n';
std::cout << '\n';
std::cout << "E.call_f(): " << E.call_f() << '\n';
std::cout << "move(E).call_f(): " << std::move(E).call_f() << '\n';
std::cout << '\n';
std::cout << "t_call_f(E): " << t_call_f(E) << '\n';
std::cout << "t_call_f(std::move(E)): " << t_call_f(std::move(E)) << '\n';
std::cout << '\n';
std::cout << "E::E_t_call_f(E): " << Experiment::E_t_call_f(E) << '\n';
std::cout << "E::E_t_call_f(std::move(E)): " << Experiment::E_t_call_f(std::move(E)) << '\n';
}
In the resulting output it is the third line that's surprising: The type of std::forward<Experiment>(*this) for an lvalue reference to *this is an rvalue reference.
E.f(): f()&
move(E).f(): f()&&
call_f()& E.call_f(): f()&&
call_f()&& move(E).call_f(): f()&&
t_call_f(T&& t) t_call_f(E): f()&
t_call_f(T&& t) t_call_f(std::move(E)): f()&&
E_t_call_f(T&& t) E::E_t_call_f(E): f()&
E_t_call_f(T&& t) E::E_t_call_f(std::move(E)): f()&&
I would like to assign a pointer to a lambda function, in which the lambda function is taking variables passed by reference, not by value.
int main() {
// what I can do, but not quite what I want
auto funcy = [](const double i ) {
std:: cout << "this is i: " << i << std::endl;
};
void(*lptr)(double); // OK
lptr = funcy;
lptr(1);
// TODO: make a variable that points to this lambda work
auto funcy2 = [](const double &i ) {
std:: cout << "this is i: " << i << std::endl;
};
void(*lptr2)(double *); // BROKE
lptr2 = funcy2;
lptr2(1);
return 0;
}
Is it possible to do this?
Thanks for your time.
Edit: This post is different from Passing capturing lambda as function pointer because I have no idea what that one is saying.
Answered by #sweenish in the comments. The "function signature" has to match. It's actually "pretty straightforward".
void(*lptr2)(const double&); // FIXED
lptr2 = funcy2;
lptr2(5);
The best would be that the type of the function pointer would match the type of the lambda function. This will be much more simple and is most likely the solution that you want.
By using pointers everywhere
auto funcy2 = [](double *i) {
std::cout << "this is i: " << *i << std::endl;
};
void(*lptr2)(double *); // matches
lptr2 = funcy2;
double i = 1;
lptr2(&i);
... or even better, references everywhere:
auto funcy2 = [](const double &i) {
std::cout << "this is i: " << i << std::endl;
};
void(*lptr2)(const double &); // works, the type match the lambda parameter
lptr2 = funcy2;
lptr2(1);
If you really want to assign a lambda to a mismatched type, you'll have to wrap it. Since there's a conversion to do, you can do it using another lambda:
static auto funcy2 = [](const double &i) {
std::cout << "this is i: " << i << std::endl;
};
auto funcy3 = [](double* i) {
funcy2(&i); // convert the pointer to a reference
};
void(*lptr2)(double *); // BROKE
lptr2 = funcy2;
lptr2(1);
I know there's plenty of questions on this already, so please bear with me on this one.
So I found this question, and I had a doubt about a modification of this.
class Blah {
public:
Blah();
Blah(int x, int y);
int x;
int y;
Blah operator =(Blah rhs);
};
Blah::Blah() {}
Blah::Blah(int xp, int yp) {
x = xp;
y = yp;
}
Blah Blah::operator =(Blah rhs) {
x = rhs.x;
y = rhs.y;
return *this;
}
int main() {
Blah b1(2, 3);
Blah b2(4, 1);
Blah b3(8, 9);
Blah b4(7, 5);
b3 = b4 = b2 = b1;
cout << b3.x << ", " << b3.y << endl;
cout << b4.x << ", " << b4.y << endl;
cout << b2.x << ", " << b2.y << endl;
cout << b1.x << ", " << b1.y << endl;
return 0;
}
So I haven't used return by reference here, while overloading the = operator, and I still get the expected output.
Why should I return by reference? The only difference I see is that copy constructor is called while returning by value but no copy constructor is called while returning by reference.
Could someone please dumb things down for me and explain the concept/idea behind returning by reference? It was taught in my class around almost a year ago, and I still don't understand it.
There is no strict right and wrong here. You can do weird things with operator overloads and sometimes it is appropriate. However, there is rarely a good reason to return a new instance from operator=.
The return value is to enable chaining. Your test for chaining is incomplete. Your line:
b3 = b4 = b2 = b1;
is the same as
b3 = (b4 = (b2 = b1));
And you see expected output for this case. However, chaining like this
(b3 = b4) = b1;
is expected to first assign b4 to b3 then assign b1 to b3. Or you might want to call a method on the returned reference:
(b3 = b4).foo();
As you return a copy, the second assignment will be to a temporary and the member function foo will be called on a temporary, not on b3 as expected. To see this in action consider the output of this
int main() {
Blah b1(2, 3);
Blah b2(4, 1);
Blah b3(8, 9);
Blah b4(7, 5);
(b3 = b4) = b1;
cout << b3.x << ", " << b3.y << endl;
cout << b1.x << ", " << b1.y << endl;
return 0;
}
when returning a copy:
7, 5
2, 3
and when returning a reference:
2, 3
2, 3
The much simpler reason is that you do not want to return a copy when there is no need to make a copy.
Why return by reference while overloading = operator?
Because:
Copying is sometimes expensive, in which case it is good to avoid.
It is conventional. That is also how the built in assignment operators of fundamental types, compiler generated assignment operators of classes, and all the assignment operators of standard types (as far as I know) work.
Given that the special member functions that you've defined don't do anything special, I recommend following class definition instead:
struct Blah {
int x;
int y;
};
Some discussion warns about dangling reference, with R-Value reference. I do not see any dangling reference in the following example as DTOR was called when main() terminates. Am I missing something?
class test_ctor
{
public:
explicit
test_ctor(int x = 1):_x(x)
{
std::cout << "CTOR: " << _x << "\n";
}
~test_ctor()
{
std::cout << "DTOR: " << _x << "\n";
}
test_ctor(test_ctor const & y) = default;
test_ctor(test_ctor && y) = default;
int _x;
};
test_ctor test_rvalue()
{
test_ctor test = test_ctor(2);
return test;
}
Now I can use the above code in two ways:
int main(int argc, const char * argv[]) {
auto test = test_rvalue();
std::cout << " test: " << test._x << " \n";
return 0;
}
Or
int main(int argc, const char * argv[]) {
auto && test = test_rvalue();
std::cout << " test: " << test._x << " \n";
return 0;
}
both case has the same output:
CTOR: 2
test: 2
DTOR: 2
Which means both are efficient ways to return object. Are there any side effects in r-value reference?
In c++11:
auto test = test_rvalue(); moves the return value of test_rvalue() into test. This move is then elided by every non-brain damaged compiler so it never happens. The move constructor still needs to exist, but is never called, and any side effects of moving do not occur.
auto&& test = test_rvalue(); binds an rvalue reference to the temporary returned by test_rvalue(). The temporaries lifetime is extended to match that of the reference.
In c++17:
auto test = test_rvalue(); the prvalue return value of test_rvalue() is used to directly construct the variable test. No move, elided or not, occurs.
The auto&& case remains unchanged from c++11.
I am trying to understand how lambdas work in C++ in depth. I have written the following piece of code.
#include <iostream>
#include <functional>
struct A
{
A() { std::cout << "A" << (data = ++count) << ' '; }
A(const A& a) { std::cout << "cA" << (data = a.data + 20) << ' '; }
A(A&& a) { std::cout << "mA" << (data = std::move(a.data) + 10) << ' '; }
~A() { std::cout << "dA" << data << ' '; }
int data;
static int count;
};
int A::count = 0;
void f(A& a, std::function<void(A)> f)
{
std::cout << "( ";
f(a);
std::cout << ") ";
}
int main()
{
A temp, x;
auto fun = [=](A a) {std::cout << a.data << '|' << x.data << ' ';};
std::cout << "| ";
f(temp, fun);
std::cout << "| ";
}
The output is below.
A1 A2 cA22 | cA42 mA52 dA42 ( cA21 mA31 31|52 dA31 dA21 ) dA52 | dA22 dA2 dA1
This is quite clear to me, except for the 'mA52' move constructor call. Note that I am using variable capture by value, so without the move constructor, the copy-constructor would be called here. Why is there an additional copy/move at this step? One would expect the object to be copied only once when fun is passed by value as an argument to f. Furthermore, the first copy of the object is immediately destroyed. Why? What is this intermediary copy?
Let's call your lambda type L. It's unnamed, but it gets confusing to refer to it without a name.
The constructor std::function<void(A)>(L l) takes L by value. This involves creating a copy of the original fun.
The constructor then moves the lambda from l into some storage managed by the std::function<void(A)> wrapper. That move also involves moving any captured entities.
std::function<void(A)> takes the function object you pass to it by value (this is the cA42 in your output). It then moves the function object in to its internal storage (this is the mA52).