2

This is mostly a curiosity question.

I saw code like this (I'm not interested in what it does)

constexpr auto xxx = boost::hana::overload(
    [](SomeType& x){ /* x is used and something is returned */ },
    [](SomeOtherType1&){ /* no-op in this case */ },
    [](SomeOtherType2&){ /* no-op in this case */ }
);

where the latter two lambdas just ignore their argument.

Since I know that boost::hana::always is to create a function which ignores its arguments and always returns the argument passed to always, I was wandering if Hana (or another library) offers a similar function to ignore one argument (or also all arguments), such that the two lambdas can be both replaced by, say, blackHole, which I know wouldn't really be a mathematical function.

When I saw a result on cppreference for std::ignore I was hurray-ing, but no... it's a totally different thing.

Enlico
  • 23,259
  • 6
  • 48
  • 102

1 Answers1

2

So you basically are asking if there is a global function object or some class in a library that works like [](auto &&) {} when called? I do not know about such a function in the STL. C++20 adds std::identity that works like [](auto &&in){return in;} so not exactly what you want, but pretty near. Before C++20 you could abuse other functions like std::as_const or std::ignore::operator= for this, though I do not know of a function that returns void.

EDIT: Regarding std::ignore::operator=: std::ignore is defined as an object such that std::ignore = blub; has no effect for any blub. This can also be written as std::ignore.operator=(blub);. But now that I think about it, that is not that helpful, since you cannot pass that function directly to e.g. an stl-algorithm, you would have to wrap it somehow.

Btw, my advise is that you define somewhere

const static auto do_nothing = [](auto &&){};
// Requires C++14, if you have C++17 available, use
constexpr auto do_nothing = [](auto &&){};

and be done with it. Abusing some STL functions can be confusing for people reading your code while an aptly named lambda has no problem at all.

n314159
  • 4,990
  • 1
  • 5
  • 20