4

Given foo which is a vector I want to evaluate it's contents with all_of. But all I'm really trying to check is that each element evaluates to true.

I can do this by using logical_not and none_of but I would rather not use double negatives, and it feels dumb to write a lambda: [](const auto param) -> bool { return param; }

Does the standard provide me a functor that does what I want?

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • 1
    Not sure where the downvote came from. I recall seeing a question about this some time ago. I think it will be possible eventually, or that's my recollection. – AndyG Jan 07 '19 at 20:19
  • I think all the standard function objects can be found [here](https://en.cppreference.com/w/cpp/header/functional). – François Andrieux Jan 07 '19 at 20:19
  • Never thought about it, but seems like an identity functor would be useful. Doesn't look like there is one. – François Andrieux Jan 07 '19 at 20:20
  • 1
    `std::bind(std::equal_to{}, _1, true)` :) Lambda doesn't look that bad afterall... – jrok Jan 07 '19 at 20:49

1 Answers1

6

What you are looking for is std::identity which was added to C++20. It takes a parameter and returns it unchanged. It operator() looks like

template<typename T>
constexpr T&& operator()( T&& t ) const noexcept;

and it returns

std::forward<T>(t)
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • How about just std::forward then? – rubenvb Jan 07 '19 at 20:43
  • 2
    @rubenvb You could but you would have to cast it to a function pointer which would look really ugly. – NathanOliver Jan 07 '19 at 20:47
  • Ah yes the unfortunate overloaded function as functor story in templates algorithms. – rubenvb Jan 08 '19 at 09:07
  • @NathanOliver In addition to that, we will most likely no longer be allowed to take the address of `std::forward` (nor instances of most function templates in the standard library) starting from C++20, as [explained here](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0551r3.pdf). (With credits to StoryTeller who [linked to the document](https://stackoverflow.com/questions/52760580/will-specialization-of-function-templates-in-std-for-program-defined-types-no-lo).) – Arne Vogel Jan 08 '19 at 12:38