Re: Problem with std::map of function pointers
On Feb 26, 12:37 pm, "DevNull" <smor...@gmail.com> wrote:
On Feb 25, 7:43 am, "Chris Theis" <chris.theis@n o s p am.cern.ch>
wrote:
Just as a general remark: you might consider making your function table a
static map, as you most probably need only one unique instance, and wrap in
a class which also takes take of initializing, function lookup etc. IMO this
would give you cleaner and more flexible design, but naturally that's a
personal opinion.
Cheers
Chris
Done and thank you for the feedback!
You should also take a look at using functor like objects. They may be
easier to use and initialise. If you have a functor super-class that
places itself into the map on initialisation (and removes itself on
destruction) then your maintenance will be easier because you just
declare a single const object for each functor type.
Simplified pseudo-code something like this:
class Functor;
map< string, const Functor * > g_functors;
class Functor {
protected:
Functor( string name ) {
g_functors[ name ] = this;
}
virtual ~Functor() {
}
public:
virtual void execute( State * ) = 0;
};
Now for each one you just do this:
const class Print : class Functor {
public:
Print() : Functor( "print" ) {}
void execute( State * ) const {
// Whatever it does
}
} c_print;
This saves you from adding a function and remembering to add it to the
map as that is done automatically.
It also makes it easy to extend as you can just dynamically load
additional code at the time of executions (i.e. on Windows use
LoadLibrary to fetch a new DLL, which can even be specified on the
command line - I'm sure there must be something similar on UNIX
variants) and all of the new functions in the new code will
automatically become available.
This solution is more decoupled that storing raw function pointers. It
also allows for the objects to be initialised in different ways to
configure closely related functions. I.e.:
const class Print : class Functor {
public:
Print( ostream &stream, string name ) : Functor( name ),
m_stream( ostream ) {}
void execute( State * ) const {
// Whatever it does
}
private:
std::ostream &m_ostream;
} c_print( std::out, "print" ), c_log( g_mylogstream, "log" );
K