I just want to know what is the purpose of std::identity? I could not find anything useful on web. I know how it is implemented :
template <typename T>
struct identity
{
T operator()(T x) const { return x; }
};
why do we actually need this?
I just want to know what is the purpose of std::identity? I could not find anything useful on web. I know how it is implemented :
template <typename T>
struct identity
{
T operator()(T x) const { return x; }
};
why do we actually need this?
Other people already answered the question - it's useful for things like a default for a function-type template parameter, and for haskell-style functional programming.
But your example implementation is not correct. Your code would perform a value copy, which std::identity
does not do - it perfectly forwards. It's also constexpr
and is transparent.
So this is an example of how it would be implemented, I believe:
struct identity
{
using is_transparent = void;
template <typename T>
constexpr T&& operator()(T&& t) const noexcept
{
return std::forward<T>(t);
}
};
Standard (up to C++20) doesn't have std::identity
, all proposals mentioning it have been removed. When initially suggested, it was supposed to serve the same purpose as std::forward
serves in accepted standard, but it conflicted with non-standard extensions and after several iterations was finally removed.
C++20 has std::identity
back: https://en.cppreference.com/w/cpp/utility/functional/identity
std::identity
. See en.cppreference.com/w/cpp/utility/functional/identity –
Sixtyfourmo The struct you have in your code is the identity function T -> T
where T is a template parameter. This function isn't useful on its own, but may be useful in other contexts where you need to pass a function parameter and the identify function is the one you want insert there. It's generally useful as a sort-of "do nothing" function.
As to std::identity
, I can find no evidence that this struct exists in the C++ standard library.
While not relevant at the time of the question being asked, C++20 adds std::identity
which seem to come from Ranges
proposal. Here is its previous definition from Ranges TS
where the main usage of it is explained as:
It is used as the default projection for all Ranges TS algorithms.
I don't have std::identity
in my libraries, but it should be a useful tool to copy a vector into another one without the nullptr
objects in it via std::copy_if
.
© 2022 - 2024 — McMap. All rights reserved.
std::identity
, all proposals have been removed. You might consider this as a hint. – Stipend