A coworker approached me today with an interesting problem and I figured I’d talk about the crazy acrobatics that solved it.
He wanted to fill out a list of operations to perform that could be registered easily “at compile time”, so that the list could be traversed later to perform these operations. Basically, he wanted his code to look something like this:
[cpp]
typedef std::map< const char *, void (*)( void ) > WorkItemList;
static WorkItemList sWork;
void some_function( void ) {
// Do some work
}
REGISTER( "operation 1", some_function );
REGISTER( "operation 2", some_function );
void some_other_function( void ) {
// Do some work
}
REGISTER( "operation 3", some_other_function );
REGISTER( "operation 4", some_other_function );
REGISTER( "operation 5", some_other_function );
// Later
void DoWork( const char *workItem ) {
WorkItemList::iterator iter = sWork.find( workItem );
if (iter != sWork.end())
iter->second();
}
[/cpp]
So how do you make this work?
Continue reading →