Is there a reason why there is not std::identity in the standard library?

Viewed 1248

When dealing with generic code in C++, I would find a std::identity functor (like std::negate) very useful. Is there a particular reason why this is not present in the standard library?

2 Answers

Since C++20, there is an std::identity functor type with an operator() template member function. This function call operator returns its argument.


For example, if you have such a function template:

template<typename T, typename Operation>
void print_collection(const T& coll, Operation op) {
    std::ostream_iterator<typename T::value_type> out(std::cout, " ");
    std::transform(std::begin(coll), std::end(coll), out, op);
    std::cout << '\n';
}

and wanted to print the elements of vec:

std::vector vec = {1, 2, 3};

you would do something like:

print_collection(vec, [](auto val) { return val; });

With std::identity, you could do:

print_collection(vec, std::identity());

The line above seems to specify this intention more clearly.

Related