C++ routine returning function - c++11

I have the following code which work fine. I am trying to understand the syntax. The return statement has std::plus<double>(). The double over here has the return value data type. But the function definition has the return type as std::function<double(double, double)> which indicates two double parameters. How do these two relate to each other?
#include <functional>
#include <iostream>
using namespace std;
std::function<double(double, double)> GetFunction()
{
return std::plus<double>();
}
int main()
{
auto operation = GetFunction();
int a = operation(1, 4);
std::cout << std::plus<>{}(1, 4) << '\n';
return 0;
}

There is an implicit conversion from std::plus<double> to std::function<double(double,double)>, because the former has a member call operator double operator()(double, double). See the documentation for std::function constructors.

In std::function<double(double, double)>:
The first double is the return type of the function. You can remember that by realizing that it's on the left, just like in a normal function definition.
The doubles in parentheses are the parameter types of the function, just like in a normal function definition; minus the parameter names. There are 2 since the plus function takes 2 doubles.
This makes sense if you think about it. The plus function/operator is a binary operator, meaning it takes 2 parameters of a type, and returns a single value of the same type. This is why you only need to specify a single type when you write std::plus<double>; the parameters and the return type must be the same type. It would be error prone and useless to force the caller to specify the same type 3 times.

If your question is, why there is only one double in the template parameter of std::plus but three in std::function, then the answer is this:
For std::plus, both parameters and the returntype always have to be the same, so you only have to specify it once.
std::function on the other hand can hold any function like object with any combination of parameters and returntypes, so you have to basically state each of those types individually.

Related

Casting to rvalue reference to "force" a move in a return value - clarification

Ok, I am starting to get the jist of rvalue references (I think). I have this code snippet that I was writing:
#include <iostream>
using namespace std;
std::string get_string()
{
std::string str{"here is your string\n"};
return std::move(str); // <----- cast here?
}
int main ()
{
std::string my_string = std::move(get_string()); // <----- or cast here?
std::cout << my_string;
return 0;
}
So I have a simple example where I have a function that returns a copy of a string. I have read that its bad (and got the core-dumps to prove it!) to return any reference to a local temp variable so I have discounted trying that.
In the assignment in main() I don't want to copy-construct that string I want to move-construct/assign the string to avoid copying the string too much.
Q1: I return a "copy" of the temp var in get_string() - but I have cast the return value to rvalue-red. Is that pointless or is that doing anything useful?
Q2: Assuming Q1's answer is I don't need to do that. Then am I moving the fresh copy of the temp variable into my_string, or am I moving directly the temp variable str into my_string.
Q3: what is the minimum number of copies that you need in order to get a string return value stored into an "external" (in my case in main()) variable, and how do you do that (if I am not already achieving it)?
I return a "copy" of the temp var in get_string() - but I have cast the return value to rvalue-red. Is that pointless or is that doing anything useful?
You don't have to use std::move in that situation, as local variables returned by value are "implicitly moved" for you. There's a special rule in the Standard for this. In this case, your move is pessimizing as it can prevent RVO (clang warns on this).
Q2: Assuming Q1's answer is I don't need to do that. Then am I moving the fresh copy of the temp variable into my_string, or am I moving directly the temp variable str into my_string.
You don't need to std::move the result of calling get_string(). get_string() is a prvalue, which means that the move constructor of my_string will automatically be called (pre-C++17). In C++17 and above, mandatory copy elision will ensure that no moves/copies happen (with prvalues).
Q3: what is the minimum number of copies that you need in order to get a string return value stored into an "external" (in my case in main()) variable, and how do you do that (if I am not already achieving it)?
Depends on the Standard and on whether or not RVO takes place. If RVO takes place, you will have 0 copies and 0 moves. If you're targeting C++17 and initializing from a prvalue, you are guaranteed to have 0 copies and 0 moves. If neither take place, you'll probably have a single move - I don't see why any copy should occur here.
You do not need to use std::move on the return value which is a local variable. The compiler does that for you:
If expression is an lvalue expression that is the (possibly parenthesized) name of an automatic storage duration object declared in the body or as a parameter of the innermost enclosing function or lambda expression, then overload resolution to select the constructor to use for initialization of the returned value is performed twice: first as if expression were an rvalue expression (thus it may select the move constructor), and if no suitable conversion is available, or if the type of the first parameter of the selected constructor is not an rvalue reference to the object's type (possibly cv-qualified), overload resolution is performed a second time, with expression considered as an lvalue (so it may select the copy constructor taking a reference to non-const).

Lambda expression in c++, OS X's clang vs GCC

A particular property of c++'s lambda expressions is to capture the variables in the scope in which they are declared. For example I can use a declared and initialized variable c in a lambda function even if 'c' is not sent as an argument, but it's captured by '[ ]':
#include<iostream>
int main ()
{int c=5; [c](int d){std::cout<<c+d<<'\n';}(5);}
The expected output is thus 10. The problem arises when at least 2 variables, one captured and the other sent as an argument, have the same name:
#include<iostream>
int main ()
{int c=5; [c](int c){std::cout<<c<<'\n';}(3);}
I think that the 2011 standard for c++ says that the captured variable has the precedence on the arguments of the lambda expression in case of coincidence of names. In fact compiling the code using GCC 4.8.1 on Linux the output I get is the expected one, 5. If I compile the same code using apple's version of clang compiler (clang-503.0.40, the one which comes with Xcode 5.1.1 on Mac OS X 10.9.4) I get the other answer, 3.
I'm trying to figure why this happens; is it just an apple's compiler bug (if the standard for the language really says that the captured 'c' has the precedence) or something similar? Can this issue be fixed?
EDIT
My teacher sent an email to GCC help desk, and they answered that it's clearly a bug of GCC compiler and to report it to Bugzilla. So Clang's behavior is the correct one!
From my understanding of the c++11 standard's points below:
5.1.2 Lambda expressions
3 The type of the lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type — called
the closure type — whose properties are described below.
...
5 The closure type for a lambda-expression has a public inline function call operator (13.5.4) whose parameters and return type are
described by the lambda-expression’s parameter-declaration-clause and
trailing-return-type respectively. This function call operator is
declared const (9.3.1) if and only if the lambda-expression’s
parameter-declaration-clause is not followed by mutable.
...
14 For each entity captured by copy, an unnamed non static data member is declared in the closure type
A lambda expression like this...
int c = 5;
[c](int c){ std::cout << c << '\n'; }
...is roughly equivalent to a class/struct like this:
struct lambda
{
int c; // captured c
void operator()(int c) const
{
std::cout << c << '\n';
}
};
So I would expect the parameter to hide the captured member.
EDIT:
In point 14 from the standard (quoted above) it would seem the data member created from the captured variable is * unnamed *. The mechanism by which is it referenced appears to be independent of the normal identifier lookups:
17 Every id-expression that is an odr-use (3.2) of an entity captured by copy is transformed into an access to the corresponding unnamed data member of the closure type.
It is unclear from my reading of the standard if this transformation should take precedence over parameter symbol lookup.
So perhaps this should be marked as UB (undefined behaviour)?
From the C++11 Standard, 5.1.2 "Lambda expressions" [expr.prim.lambda] #7:
The lambda-expression’s compound-statement yields the function-body (8.4) of the function call operator,
but for purposes of name lookup (3.4), determining the type and value of this (9.3.2) and transforming id-expressions
referring to non-static class members into class member access expressions using (*this) (9.3.1),
the compound-statement is considered in the context of the lambda-expression.
Also, from 3.3.3 "Block scope" [basic.scope.local] #2:
The potential scope of a function parameter name (including one appearing in a lambda-declarator) or of
a function-local predefined variable in a function definition (8.4) begins at its point of declaration.
Names in a capture list are not declarations and therefore do not affect name lookup. The capture list just allows you to use the local variables; it does not introduce their names into the lambda's scope. Example:
int i, j;
int main()
{
int i = 0;
[](){ i; }; // Error: Odr-uses non-static local variable without capturing it
[](){ j; }; // OK
}
So, since the parameters to a lambda are in an inner block scope, and since name lookup is done in the context of the lambda expression (not, say, the generated class), the parameter names indeed hide the variable names in the enclosing function.

Move constructor not getting called? (C++11)

In the following example, why doesn't the move constructor get called in the construction of 'copy' inside fun, even though the 'src' argument of 'fun' is explicitly a rvalue reference and is only used in that construction?
struct Toy {
int data;
Toy(): data(0)
{
log("Constructed");
}
Toy(Toy const& src): data(src.data)
{
log("Copy-constructed");
}
Toy(Toy&& src): data(src.data)
{
log("Move-constructed");
}
};
Toy fun(Toy&& src)
{
Toy copy(src);
copy.data = 777;
return copy;
}
Toy toy(fun(Toy())); // LOG: Constructed Copy-constructed
While Bob && b is an rvalue reference, all named use of data after construction is using it as an lvalue.
So Bob&& b will only bind to rvalues, but when you use it it will not move.
The only ways to get an rvalue reference are:
A value without a name, such as a temporary return value or result of a cast.
Use of a local value variable in a simple return x; statement.
Explicitly casting to an rvalue, such as with std::move or std::forward.
This prevents data from being silently moved from on one line and then used on the next. It can help to think of rvalue as being 'I the programmer say this is not needed after this expression' at use, and 'only take things that are not needed afterwards' in function parameters. The temporary/return exceptions above are two spots the compiler can relatively safely guarantee this itself.
Finally, note that universal references (auto&& and T&&) look like rvalue references but sometimes are not.

Do I need to use std::move again?

For below code, I want to use the std::move to improve the efficiency. I have two functions, the first function uses std::move, and the second function just calls the first function. So, do I need to use std::move again in the function "vector convertToString()"? Why and why not? Thank you.
class Entity_PortBreakMeasure
{
public:
Entity_PortBreakMeasure(){}
int portfolioId;
string portfolioName;
int businessDate;
string assetType;
string currency;
string country;
string industry;
string indicator;
double value;
inline double operator()()
{
return value;
}
static vector<string> convertToString(Entity_PortBreakMeasure& pbm)
{
//PORTFOLIOID INDUSTRY CURRENCY COUNTRY BUSINESSDATE ASSETTYPE INDICATOR VALUE PORTFOLIONAME
vector<string> result;
result.push_back(boost::lexical_cast<string>(pbm.portfolioId));
result.push_back(pbm.industry);
result.push_back(pbm.currency);
result.push_back(pbm.country);
result.push_back(Date(pbm.businessDate).ToString());
result.push_back(pbm.assetType);
result.push_back(pbm.indicator);
result.push_back(boost::lexical_cast<string>(pbm.value));
result.push_back(pbm.portfolioName);
return std::move(result);
}
vector<string> convertToString()
{
return convertToString(*this);
}
move() shouldn't be used for either of these functions.
In the first function, you're returning a local variable. Without move(), most (all?) compilers will perform NRVO and you won't get a copy or a move -- the returned variable will be constructed directly in the returned value for the caller. Even if the compiler is, for some reason, unable to do NRVO, local variables become r-values when used as the argument to a return, so you'll get a move anyway. Using move() here serves only to inhibit NRVO and force the compiler to do a move (or a copy in the event that the move isn't viable).
In the second function, you're returning an r-value already, since the first function returns by value. move() here doesn't add anything but complexity (which might possibly confuse an optimizer into producing suboptimal code or failing to do copy elision).

Using Generic with Func as a parameter

My code is simply:
public override C Calculator<C>(Team[] teams, Func<Team, C> calculatorFunc)
{
return teams.Average(calculatorFunc);
}
I get this error:
Error 2 The type arguments for method 'System.Linq.Enumerable.Average(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
How can I fix this?
You can't - at least in the current form. There is no Average overload available that works on completely generic values (i.e. for all types C as you specified).
Average needs lists of numbers (int, double, float ...) or a conversion function that produces numbers. In the current form, you could call Calculator<string> and it would make absolutely no sense to compute the average of strings.
You'll just have to restrict the method to a specific numeric type (or provide overloads), but generics simply won't work.
The Enumerable.Average method does not have an overload which works on a generic type. You're trying to call Average<TSource>(IEnumerable<TSource>, Func<TSource, C>), which does not exist.
In order to use average, you'll need to specify one of the types (for C) that actually exists, such as double, decimal, etc.
Instead of writing:
Calculate(team, calcFunc);
You will have to write:
Calculate<MyClass>(team, calcFunc);
However, you really should know what calculatorFunc is returning --- I'm going to assume that all of the ones you use return the same value type (whether it be decimal or int of float). In which case, you could define it as:
public override int Calculator(Team[] teams, Func<Team, int> calculatorFunc)
{
return teams.Average(calculatorFunc);
}
Then you have no generics in the declaration at all to worry about.

Resources