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?

5
  • "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. Commented Aug 10, 2021 at 11:38
  • 2
    Even solving the overload issue, see can-i-take-the-address-of-a-function-defined-in-standard-library. Commented Aug 10, 2021 at 11:40
  • 1
    @StoryTeller-UnslanderMonica: and passing lambda is even more prone to inlining than function pointer :) Commented Aug 10, 2021 at 11:41
  • 1
    @rprospero: it would be something like static_cast<bool (*)(const std::pair<int, bool>&)>(std::get<bool>) (if allowed for std::get). lambda seems better ;) Commented Aug 10, 2021 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. Commented Aug 10, 2021 at 11:45

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.