//neccessary headfiles are included
//"same" function
class fun_with{
intoperator()(int x){return x+1;}// function object
};
auto fun_nwith = [](int x){return x+1;}; //lambda function
int main(){
...//declaration of container"coll" and "out"
transform(coll.begin(),coll.end(),out.begin(),fun_nwith);//not wiht "()"
transform(coll.begin(),coll.end(),out.begin(),fun_with());//with "()" on contrast
}
confusion on the necessity of the difference between with "()" and not with "()".Is it a better design if both with"()" or both nwith"()"? Why function object with "()" and lambda function not with "()"?
fun_with is a type. You can't pass a type as a param hence the need to use () which generates an unnamed temporary object.
Note. Don't confuse () on fun_with() with operator(). fun_with() creates a temp object with default constructor. Transform then calls operator() on this passed object.
Consider:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <vector>
#include <algorithm>
class fun_with {
intoperator()(int x) { return x + 1; }// function object
};
auto fun_nwith = [](int x) {return x + 1; }; //lambda function
int main() {
std::vector<int> coll, out;
transform(coll.begin(), coll.end(), out.begin(), fun_nwith);
transform(coll.begin(), coll.end(), out.begin(), fun_with {});
}
which effectively does the same but uses {} for the object constructor.
fun_nwith is a lambda variable, not a type, so can be passed.