1

I have a vector std::vector<std::pair<int, bool>> vec and I would like to know how many elemnts have the boolean set to true. The following code works:

std::count_if(vec.begin(), vec.end(), [](const auto& x) { return std::get<bool>(x); });

However, it bothers me that I'm creating a lambda that does nothing more than call another function with the exact same parameter. I expected that I would be able to write:

std::count_if(vec.begin(), vec.end(), std::get<bool>);

But I get a message that the compiler cannot resolve the _Predicate template. I understand this to be because the compiler cannot resolve the highly overloaded std::get function in this context. Is there a way to specify the correct version of std::get beyond wrapping it inside the lambda?

rprospero
  • 913
  • 11
  • 26
  • *"However, it bothers me"* - Why? And please don't say "efficiency". This idiom is very prone to inlining. But even then, you'd be told to measure carefully. – StoryTeller - Unslander Monica Aug 10 '21 at 11:38
  • 2
    Even solving the overload issue, see [can-i-take-the-address-of-a-function-defined-in-standard-library](https://stackoverflow.com/questions/55687044/can-i-take-the-address-of-a-function-defined-in-standard-library). – Jarod42 Aug 10 '21 at 11:40
  • 1
    @StoryTeller-UnslanderMonica: and passing lambda is even more prone to inlining than function pointer :) – Jarod42 Aug 10 '21 at 11:41
  • 1
    @rprospero: it would be something like `static_cast&)>(std::get)` (if allowed for `std::get`). lambda seems better ;) – Jarod42 Aug 10 '21 at 11:43
  • @StoryTeller-UnslanderMonica honestly, my co-workers all thought that the second version was clearer to read, but the linked answer obviously shows that it's not legal syntax, so our legibility concerns are moot. – rprospero Aug 10 '21 at 11:45

0 Answers0