std::identity

来自cppreference.com
< cpp‎ | utility‎ | functional
 
 
 
函数对象
函数调用
(C++17)(C++23)
恒等函数对象
identity
(C++20)
旧式绑定器与适配器
(C++17 前*)
(C++17 前*)
(C++17 前*)
(C++17 前*)
(C++17 前*)(C++17 前*)(C++17 前*)(C++17 前*)
(C++20 前*)
(C++20 前*)
(C++17 前*)(C++17 前*)
(C++17 前*)(C++17 前*)

(C++17 前*)
(C++17 前*)(C++17 前*)(C++17 前*)(C++17 前*)
(C++20 前*)
(C++20 前*)
 
在标头 <functional> 定义
struct identity;
(C++20 起)

std::identity 是函数对象类型,它的 operator() 直接返回未经更改的实参。

目录

[编辑]成员类型

类型 定义
is_transparent未指定

[编辑]成员函数

operator()
返回不更改的实参
(公开成员函数)

std::identity::operator()

template<class T >
constexpr T&& operator()( T&& t )constnoexcept;

返回 std::forward<T>(t)

参数

t - 要返回的实参

返回值

std::forward<T>(t)

[编辑]注解

std::identity受约束算法中担当默认投影。通常不需要直接使用它。

[编辑]示例

#include <algorithm>#include <functional>#include <iostream>#include <ranges>#include <string>   struct Pair {int n;std::string s;friendstd::ostream& operator<<(std::ostream& os, const Pair& p){return os <<"{ "<< p.n<<", "<< p.s<<" }";}};   // 范围打印器能打印投影(修改)后的范围元素。template<std::ranges::input_range R, typename Projection = std::identity>//<- 注意默认投影void print(std::string_viewconst rem, R&& range, Projection projection ={}){std::cout<< rem <<'{'; std::ranges::for_each( range, [O =0](constauto& o) mutable {std::cout<<(O++?", ":"")<< o;}, projection );std::cout<<"}\n";}   int main(){constauto v ={Pair{1, "one"}, {2, "two"}, {3, "three"}};   print("将 std::identity 用作投影打印:", v); print("投影 Pair::n:", v, &Pair::n); print("投影 Pair::s:", v, &Pair::s); print("将自定义闭包用作投影打印:", v, [](Pair const& p){returnstd::to_string(p.n)+':'+ p.s;});}

输出:

将 std::identity 用作投影打印:{{1, one}, {2, two}, {3, three}} 投影 Pair::n:{1, 2, 3} 投影 Pair::s:{one, two, three} 将自定义闭包用作投影打印:{1:one, 2:two, 3:three}

[编辑]参阅

返回不更改的类型实参
(类模板)[编辑]
close