Reputation: 21443
I have a map containing boost::function
values, as defined below:
std::map <std::string, boost::function<std::string (std::string, int)> > handlers;
Let us say I define the following function:
using namespace std;
string substring (string input, int index = 0){
if (index <= 0){
return input;
}
stringstream ss;
for (int j = index; j<input.length(); j++){
ss << input[j];
}
return ss.str();
}
I would like to be able to store this in the handlers map, but WITH it's optional parameter. Does boost have a way to perform this? I have looked at boost::optional
, but that doesn't seem to do what I want.
EDIT
To give a little more background, there are a few handlers that require extra arguments, such as a pointer to a dictionary (typedef std::map < std::string, std::string > dictionary
) or something, because they make changes to that dictionary. However, the majority of the handlers do not touch the dictionary in question, but, in order to store them all in the same map, they all must take the same arguments (have the same template for boost::function
). The goal is to make the functions that don't deal with the dictionary at all usable without having to either A) create a dictionary for the sole purpose of passing it and not using it or B) copy the code verbatim into another function that doesn't require that argument.
The code above is a simplified example of what I am doing.
Upvotes: 2
Views: 2014
Reputation: 15768
The short answer: This is not possible in C++ without a lot of additional code.
The long answer:
Default values for function arguments in C++ are only used when they are needed in a context where the function's name appears. If you call a function through other means (like a function pointer, or boost::function/std::function
, the information about there possibly being default arguments is not available to the compiler, so it can't fill them in for you.
As a background, this is how default arguments work in C++:
When you have the expression substring(MyString)
(with std::string MyString = "something"
), then the compiler looks for all functions called substring
and finds string substring(string, int=0)
. This function takes two parameters, one of which can have a default value, which makes the function viable. To actually call the function, the compiler changes the source code so that it reads substring(MyString, 0)
and proceeds to generate code based on that adaptation.
To be able to use default values with an indirect call, like through boost::function
, you effectively have to emulate the default argument mechanism of the compiler.
Upvotes: 2