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 );
}
};
It’s an optimization step for templated predicates.
It’s not a matter of a functor being easier to use than a function. Both work pretty much the same way in boost and STL contexts.
How they differ is in template instantiation.
Imagine a trivial template function that requires a predicate
Using a function will instantiate a template instance with a function pointer.
Using a functor will instantiate a template instance with a specific functor type.
With the functor, the specific functionality is now well defined and the struct being passed in is likely not used and can be optimized out.