具有单个参数的布尔函数的映射

时间:2017-05-10 11:06:49

标签: c++ lambda runtime-error

我没有很多编写C ++的经验,而且我正在努力解决问题。下面的代码是从片段中拼凑而成的。我正在写一个类,我希望它有一个字符串键和函数值的属性映射:

std::map< std::string, std::function<bool(std::string)> > selection_filters;

然后我想按如下方式添加对:

auto some_func = [] (std::string value) { return value == "some_val"; };

selection_filters["some_key"] = some_func;
//or
selection_filters.insert(std::make_pair("some_key", some_func));

这样我就可以:

if ( selection_filters["some_key"]("function param") == true ) {

//etc..

}

这会编译,但会在运行时抛出错误:

terminating with uncaught exception of type std::__1::bad_function_call: std::exception

我怀疑这可能与地图定义中std::function<bool(std::string)>与lambda函数[] (std::string value) { ... };

的使用之间的差异有关

我非常希望保留lambda函数的使用以及通过地图上的下标运算符访问函数的可能性(map['some_key'](..)),但是我对C ++的了解并不足以提出溶液

有人可以指出我正在制作的错误(以及为什么会被抛出;我想学习)并提供改进建议

1 个答案:

答案 0 :(得分:3)

请参阅What causes std::bad_function_call?

缺少或清空功能。在调用函数之前,请务必检查地图中是否存在“some_key”,

if(selection_filters.find("some_key") != selection_filters.end())

或至少检查该函数是否具有有效目标:

if(selection_filters["some_key"])

当您在[]上使用std::map运算符时,如果它不在地图中,它将插入默认构造对象(或零)。这可能(并且将会)导致您未明确设置的键的大量无效条目。