views:

62

answers:

3

I have an unordered_map of functions that should be called on an object when an XML file is parsed.
I have found that boost::function has a base class named boost::function_base, however as expected I cannot invoke it because I don't have the signuture of the function.
Since all of those functions are setter functions, I can guarantee that they return void and have only one parameter of an unknown type.
Is there any better way to resolve the type other then an if-else-if branch which I am trying to avoid?

A: 

boost::function is designed for compile time polymorphism only. Why don't you just use a regular function pointer? I.e.

typedef void (*function_type)(void *);
Billy ONeal
+2  A: 

Use a boost::variant is the best way to go. How could you possibly invoke a function with an unknown parameter type, anyway?

DeadMG
+1 i second that. A variant knows what type is stored, so he can avoid the if-else-if branch.
Johannes Schaub - litb
@Johannes Schaub - litb: But then how can I just call the function? I still need to know the type I am resolving.
the_drow
@the_drow look into visitation. boost.variant manual has information on it.
Johannes Schaub - litb
@Johannes Schaub - litb: So I still need to specify the signuture of my functions, right?
the_drow
A: 

If the type of the object you want to pass into the function is not related to the type of the XML node being parsed (e.g. a "tree_parse_handler" object), then bind the object before you save your function in the list.

std::list<boost::function<void()> > functions_to_call;

functions_to_call.push_back(boost::bind(&myClass::myCallbackMethod, myInstance));

If it is related, you need to rethink your problem -- you are basically constrained to pick a type to carry information to the callback.

chrispy
The type of the object that I want to pass to the function is related to the attribute of the node I am parsing.
the_drow
@the_drow Be more specific in your question and we may be able to be more helpful!
chrispy