0

In C++ we can't pass certain functions to algorithms. I suspect it's when they're overload or templates:

vector<string> xs = {"12", "34"};
vector<int> ys = transform_to_vec(xs, stoi); // compile error

The simplest workaround I've found is:

#define PLEASE(F) ([](auto&& x) { return F(forward<decltype(x)>(x)); })
vector<int> ys = transform_to_vec(xs, PLEASE(stoi));

Is there a better way?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
tamas.kenez
  • 7,301
  • 4
  • 24
  • 34
  • If you can do it with a macro, you can certainly do it with a template.. – Brandon Feb 14 '20 at 21:30
  • 2
    @Brandon Good luck with that. OP: this is the correct idiom to use. Either write a lambda or write a macro that generates it for you. – NathanOliver Feb 14 '20 at 21:31
  • 1
    FWIW you can make your macro slightly more generic/correct like I do here: https://stackoverflow.com/a/54182576/4342498 (also might be considered a dupe target) – NathanOliver Feb 14 '20 at 21:32

0 Answers0