I am a relatively new c++ user. I would have a question about functions. I want to define a function which accepts a number of parameters, say defined previously somewhere in the code, and which returns a function with an unknown variable, say x. I found a possible solution in the following example with the operator overloading, something like:
class f{
public:
Real uN, uc, pc;
f(const Real uN_, const Real uc_, const Real pc_): uN(uN_), uc(uc_), pc(pc_) {}
Real operator() (const Real x) {
return uc*uN*pc*x;
}
};
Now I am not too happy with the above solution as I would like a simpler case and because I am not too sure that that one would be the cheapest way in terms of memory and computational time (I care a lot about performance). Any advice or possible alternative solution would be appreciated. Also just a link to some inherent documentation which treats the problem explaining the relative syntax would be fine.
Normally you could do this by returning a simple function pointer. Since your function apparently needs to "remember" some values, a function object is the way to go. To potentially improve performance, pass the Real values as constant references (unless Real is just a typedef for float). If (N)RVO can be applied in the function that returns the function object, you will just have the cost of copying three Real values. That's about as cheap as it can get (in terms of computational time and memory).
You should also mark operator() as const, since it does not modify any members. That will allow you to invoke operator() on a temporary f object as well.
Hello Athar,
thanks for your quick reply. Real is just a typedef for float. What I propose is already a function object (or functor), right? So you would improve it like:
class f{
public:
Real uN, uc, pc;
f(const Real &uN_, const Real &uc_, const Real &pc_): uN(uN_), uc(uc_), pc(pc_) {}
const Real operator() (const Real x) {
return uc*uN*pc*x;
}
};
Real is just a typedef for float. What I propose is already a function object (or functor), right?
It is. Passing the values as references would be better if Real was a more complex and larger type than float. However copying a float is not more expensive than copying a pointer (which is what a reference internally is), so using references will not produce faster code in this case.
I would write it as follows:
1 2 3 4 5
struct f{ //since all members are public anyway
Real uN, uc, pc;
f(Real uN_,Real uc_,Real pc_): uN(uN_), uc(uc_), pc(pc_) {}
Real operator() (Real x) const {return uc*uN*pc*x;} //marking operator() as const
};
BTW, is it right to say _const real &uN_ instead of _real const &uN_?
If you mean const Real& vs. Real const& - both are allowed and both have the same meaning. So it's just a matter of preference.