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?
views:
62answers:
3
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
2010-09-12 18:27:13
+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
2010-09-12 18:30:19
+1 i second that. A variant knows what type is stored, so he can avoid the if-else-if branch.
Johannes Schaub - litb
2010-09-12 20:17:48
@Johannes Schaub - litb: But then how can I just call the function? I still need to know the type I am resolving.
the_drow
2010-09-12 21:57:59
@the_drow look into visitation. boost.variant manual has information on it.
Johannes Schaub - litb
2010-09-12 22:10:46
@Johannes Schaub - litb: So I still need to specify the signuture of my functions, right?
the_drow
2010-09-13 07:41:16
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
2010-09-13 16:09:03