std:: identity
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Old binders and adaptors | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
定义于头文件
<functional>
|
||
|
struct
identity
;
|
(C++20 起) | |
std::identity
是一个函数对象类型,其
operator
(
)
会原封不动地返回其参数。
目录 |
成员类型
| 类型 | 定义 |
is_transparent
|
未指定 |
成员函数
|
operator()
|
返回未经修改的实参
(公开成员函数) |
std::identity:: operator()
|
template
<
class
T
>
constexpr T && operator ( ) ( T && t ) const noexcept ; |
||
返回 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; friend std::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_view const rem, R&& range, Projection projection = {}) { std::cout << rem << '{'; std::ranges::for_each( range, [O = 0](const auto& o) mutable { std::cout << (O++ ? ", " : "") << o; }, projection ); std::cout << "}\n"; } int main() { const auto 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) { return std::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}
参见
|
(C++20)
|
返回未经修改的类型实参
(类模板) |