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

荒凉一梦 提交于 2019-12-10 14:04:38

问题


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?


回答1:


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.




回答2:


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




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/41767240/what-is-stdidentity-and-how-it-is-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!