MEMS
MEMS

Reputation: 647

what is std::identity and how it is used?

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?

Upvotes: 8

Views: 10887

Answers (5)

hadriel
hadriel

Reputation: 651

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);
        }
    };

Upvotes: 5

SergeyA
SergeyA

Reputation: 62553

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

Upvotes: 3

Predelnik
Predelnik

Reputation: 5246

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.

Upvotes: 2

Adam Hunyadi
Adam Hunyadi

Reputation: 1952

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.

Upvotes: 0

Cubic
Cubic

Reputation: 15673

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.

Upvotes: 2

Related Questions