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?
Asked
Active
Viewed 1,368 times
8

Vincent
- 57,703
- 61
- 205
- 388
-
3It was present in pre-C++11 drafts. IIRC, it was used to prevent template argument deduction in [`std::forward`](http://en.cppreference.com/w/cpp/utility/forward). Somewhere along the way, someone realized `remove_reference` was needed for `forward`, which also took care of the non-deducible context part, and maybe `identity` was no longer used by anything else, so it got dropped. – Praetorian Mar 10 '16 at 04:56
-
Interestingly, some C++ implementations seem to use a `std::_Identity` template internally. – JAB Sep 07 '16 at 14:12
2 Answers
2
Soon after std::identity was introduced, issues began to appear, starting with conflicts to pre-cpp98 definitions of std::identity appearing as extensions: https://groups.google.com/a/isocpp.org/forum/#!topic/std-proposals/vrrtKvA7cqo This site might give a little more history for it.
-
Identity can be used to prevent template argument deduction. Boost::clamp uses this trick. See also https://stackoverflow.com/questions/41767240/what-is-stdidentity-and-how-it-is-used. – gast128 Dec 11 '17 at 16:13
1
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.

JFMR
- 23,265
- 4
- 52
- 76