Sometimes I prefer to write functors, not to maintain state between function calls, but because I want to capture some arguments that are shared between function calls. As an example:
class SuperComplexAlgorithm { public: SuperComplexAlgorithm( unsigned int x, unsigned int y, unsigned int z ) : x_( x ), y_( y ), z_( z ) {} unsigned int operator()( unsigned int arg ) const { return x_ * arg * arg + y_ * arg + z_; } private:
Compared with
unsigned int superComplexAlgorithm( unsigned int x, unsigned int y, unsigned int z, unsigned int arg ) { return x * arg * arg + y * arg + z; }
The first solution has many disadvantages, in my opinion:
- Documentation that
x , y , z do is split into different places (constructor, class definition, operator() ). - A lot of boiler room code.
- Less flexible. What if I want to capture another subset of parameters?
Yes, I just realized how useful boost::bind or std::bind . Now for my question, before I start using this in many of my codes: Is there a situation where I should consider using a hand-written functional without saving the binding arguments in a simple function?
source share