I have a number of functions that take references to typedef
'd data types, as below:
typedef std::map<string, string> dict;
union ret_t{
int i;
long l;
double d;
};
ret_t func1(char* bytes, dict &d){
//blah blah
}
ret_t func2(char* bytes, dict &d){
//blah blah 2
}
I also have a map of handler functions, using boost::function
as defined below:
std::map <int, boost::function< ret_t (char*, dict) > > handlers;
I defined this so that, with the >100 handler functions that I am using, I can simply read a key and call handlers[key](bytes, d);
and have my function execute, only required 3 if/elses for my different data types (knowing the data type i need is another issue I won't get into. It's irrelevant to the question). This works as expected.
My issue is that a small number of the functions do not utilize the dictionary, and would be useful in a context outside the handlers (for instance, a function that ready a stream of bytes and converts it to a long int). In order to call this function from a context in which I do not have a dict predefined, I either have to create a useless dict that is never used:
dict d;
func1(bytes, d);
Or I have to pverride the function:
//previous definition
ret_t func1(char* bytes){
//same blah blah as before
}
When I attempt to define it with a default argument, such as NULL
or an empty dict, I get a compiler error:
default argument for 'dict& d' has type 'dict {aka std::map<std::basic_string<char>, std::basic_string<char> >}'
Is there a way to do what I want, without having to completely rewrite my code to pass pointers around instead of references?
For those functions that don't take a dictionary, create two versions. Have one that doesn't take a dictionary as a parameter and one that does but just calls the other without the dictionary. Use the former for all direct calls and the latter for dispatching like other functions that take a dictionary.