Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 926
MEMS Avatar asked Jan 20 '17 15:01

MEMS


People also ask

What is identity in c++?

Defined in header <functional> struct identity; (since C++20) std::identity is a function object type whose operator() returns its argument unchanged.

What is C++ std :: function?

Class template std::function is a general-purpose polymorphic function wrapper. Instances of std::function can store, copy, and invoke any Callable target -- functions, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.

What is the type of std :: function?

std::function is a type erasure object. That means it erases the details of how some operations happen, and provides a uniform run time interface to them.

What is std :: any?

Defined in header <any> class any; (since C++17) The class any describes a type-safe container for single values of any copy constructible type. 1) An object of class any stores an instance of any type that satisfies the constructor requirements or is empty, and this is referred to as the state of the class any object.


2 Answers

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

like image 196
SergeyA Avatar answered Nov 07 '22 01:11

SergeyA


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.

like image 24
Cubic Avatar answered Nov 07 '22 02:11

Cubic