2

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.

4

1 回答 1

2

简短的回答:如果没有大量附加代码,这在 C++ 中是不可能的。

长答案:
C++ 中函数参数的默认值仅在函数名称出现的上下文中需要它们时使用。如果您通过其他方式调用函数(例如函数指针或boost::function/std::function,则编译器无法获得有关可能存在默认参数的信息,因此它无法为您填写它们。

作为背景,这是默认参数在 C++ 中的工作方式:
当您有表达式substring(MyString)(with std::string MyString = "something") 时,编译器会查找所有调用的函数substring并找到string substring(string, int=0). 这个函数有两个参数,其中一个可以有一个默认值,这使得函数可行。要实际调用该函数,编译器会更改源代码,以便它读取substring(MyString, 0)并继续生成基于该适配的代码。

为了能够通过间接调用(例如 through )使用默认值boost::function,您必须有效地模拟编译器的默认参数机制。

于 2013-01-02T16:48:46.853 回答