Q1. Why are callback functions used?
Q2. Are callbacks evil? Fun for those who know, for others a nightmare.
Q3. Any alternative to
Q3. Any alternative to callback?
I prefer the functor form of callback. e.g. this sort of thing:
class WidgetContainerOrProcessorOfSomeSort
{
public:
struct IWidgetFunctor
{
virtual bool operator()( const Widget& thisWidget )=0;
};
....
bool ProcessWidgets( IWidgetFunctor& callback )
{
.....
bool continueIteration = callback( widget[ idxWidget ] );
if ( !continueIteration ) return false;
.....
}
};
struct ShowWidgets : public WidgetContainerOrProcessorOfSomeSort::IWidgetFunctor
{
virtual bool operator(){ const Widget& thisWidget }
{
thisWidget.print();
return true;
}
};
WidgetContainterOrProcessorOfSomeSort wc;
wc.ProcessWidgets( ShowWidgets() );
It always seems a bit verbose for simple samples, but in the real world I find it much easier than trying to remember exactly how to construct complex function pointer declarations :-)