std::identity
来自cppreference.com
| 在标头 <functional> 定义
|
||
| |
(C++20 起) | |
std::identity 是函数对象类型,它的 operator() 直接返回未经更改的实参。
成员类型
| 类型 | 定义 |
is_transparent
|
未指定 |
成员函数
| 返回不更改的实参 (公开成员函数) |
std::identity::operator()
| |
||
返回 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) |
返回不更改的类型实参 (类模板) |