Re: map value as function pointer
mlimber wrote:
AnonMail2005@gmail.com wrote:
But function objects (e.g. from boost) will let you get around this.
That's true *if* you can supply the object instances when building the
map. See Boost's bind and mem_fn libraries.
Cheers! --M
Well before we look into better ways of doing it, the simplest way for
"free" functions.
typedef your function. Let's say your function takes a const char *
parameter and returns int.
typedef int ( *func_type ) ( const char * );
and now you can have std::map< std::string, func_type >
The alternative using a functor would be to use a single functor type
that takes a function pointer as its constructor. The advantage is only
one of clean syntax. Thus you can have a functor eg:
template< typename ReturnType, typename Param0, typename Param1 >
class function2
{
public:
typedef ReturnType ( * func_type ) ( Param0, Param1 );
private:
func_type func;
public:
function2( func_type f ) : func( f ) {}
ReturnType operator() ( Param0 p0, Param1 p1 )
{
return func( p0, p1 );
}
};
Not sure that is totally accurate (do I need (*func)(p0,p1) ? )
boost functions are similar to what I have illustrated. I can't
remember how high they go.
The other option is to use an abstract base class. Now you don't define
different functions, you define classes. That is the way I prefer doing
it, by the way.
If you have existing free-functions you want to use, you can always
create instantiations of the abstract base class that use them (or even
that take one as a parameter and use it so you need write only one such
instantiation).
Now you can have global instances of these classes - they don't have
state so are re-entrant and they don't really use up any resource in
their construction. You can also write libraries that create new
instances, and even get them to add themselves to your map, thus
providing a system of "add-ins" to your application.