timbit
timbit

Reputation: 353

Map of Boolean Functions with A Single Argument

I don't have a lot of experience writing C++ and I'm struggling with an issue. The code below is kind of scraped together from snippets. I am writing a class and I want it to have an attribute map of string keys and function values:

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

I then want to add pairs as follows:

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));

Such that I can:

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

//etc..

}

This compiles, but throws an error at runtime:

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

I suspect it may have something to do with a discrepancy between std::function<bool(std::string)> in the map definition, and the use of the lambda function [] (std::string value) { ... };

I would very much like to preserve the use of lambda functions and the possibility to access the functions through the subscript operators on the map (map['some_key'](..)) but my knowledge of C++ is not good enough to come up with a solution.

Can someone please point out the error I'm making (and why it is thrown; I want to learn) and provide suggestions for improvement?

Upvotes: 0

Views: 158

Answers (1)

James Poag
James Poag

Reputation: 2380

See What causes std::bad_function_call?

Missing or empty function. Be sure to check that "some_key" exists in the map before you call the function,

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

or at least check that the function has a valid target:

if(selection_filters["some_key"])

When you use the [] operator on an std::map, it will insert a default constructed object (or zero) if it is not already in the map. This can (and will) cause lots of invalid entries for keys that you have not explicitly set.

Upvotes: 3

Related Questions