In our code we have quite a few cases of this pattern:
class outerClass
{
struct innerStruct
{
wstring operator()( wstring value )
{
//do something
return value;
}
};
void doThing()
{
wstring initialValue;
wstring finalValue = innerStruct()( initialValue );
}
};
What's the advantage of this over:
class outerClass
{
wstring changeString( wstring value )
{
//do something
return value;
}
void doThing()
{
wstring initialValue;
wstring finalValue = changeString( initialValue );
}
};
A struct with an operator() is often called a functor, effectively acting as a "Function object". You can use these functors with many APIs, especially the STL, more easily and robustly than you can use typical function pointers. Functors being objects, they can contain state, and be parameterised during construction to create a self contained specialised handler.
I presume that often times, you have code in outerClass that wants to use these library functions (i.e. std::for_each), and so have developed this pattern to make it trivial. If you never use functors, then yes, this syntax is pointless and hard to read (and can be replaced as you suggest).
Edit: You might like Question 317450, about operator().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With