1

I'm hoping to build a std::map of lambdas with varying signatures. E.g., this works:

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

map.emplace("gt_zero", [](double a) { return a > 0; });
map.emplace("lt_zero", [](double a) { return a < 0; });

bool foo = map["gt_zero"](42); // returns true
bool bar = map["lt_zero"](42); // returns false

Below demonstrates what I'd also like to do in the same map, but it won't compile because the lambda signature doesn't match the map's:

map.emplace("equal", [](double a, double b) { return a == b; });
bool baz = map["equal"](42, 42);

Is there a way to define a std::map to accept lamdbas with different signatures?

EDIT: The above does not approximate my use case. It's for identifying my coding issue. The actual use case has knowledge of the signature.

EDIT: Thanks to the posters that pointed out the similar question Store functions with different signatures in a map. Unfortunately, the code posted in that answer does not compile for VS2017/C++17.

buttonsrtoys
  • 2,359
  • 3
  • 32
  • 52
  • 2
    That seems pretty dangerous. At the call site, how are you going to differentiate the different arities? You could "partially" apply a lambda so it only takes 1 argument, then put that in the map; *if* you know ahead of time what you'll want to check the equality against. – Carcigenicate May 24 '18 at 16:49
  • 4
    Why do you need to use the same map for both? – Barmar May 24 '18 at 16:49
  • 2
    related/dupe: https://stackoverflow.com/questions/45715219/store-functions-with-different-signatures-in-a-map – NathanOliver May 24 '18 at 16:50
  • You could map to a union or `std::variant`. But you'll need to select the particular function type at the calling location. – Barmar May 24 '18 at 17:03
  • Possible duplicate of [Store functions with different signatures in a map](https://stackoverflow.com/questions/45715219/store-functions-with-different-signatures-in-a-map) – Vincent Saulue-Laborde May 24 '18 at 18:09
  • You could store function pointers in the map... But why? edit: oh wait, that;s what the previous comment said. – JHBonarius May 24 '18 at 19:06
  • The answer you linked compiles fine for me in VS2017 15.7.2 (cl 19.14.26429.4) maybe update your version – PeterT May 24 '18 at 19:24

0 Answers0