std::identity
来自 cppreference.com
< cpp | utility | functional
定义在头文件 <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 << '}'; } }; // A range-printer that can print projected (modified) elements of a range. template<std::ranges::input_range R, typename Projection = std::identity> //<- Notice the default projection 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("Print using std::identity as a projection: ", v); print("Project the Pair::n: ", v, &Pair::n); print("Project the Pair::s: ", v, &Pair::s); print("Print using custom closure as a projection: ", v, [](Pair const& p) { return std::to_string(p.n) + ':' + p.s; }); }
输出
Print using std::identity as a projection: {{1, one}, {2, two}, {3, three}} Project the Pair::n: {1, 2, 3} Project the Pair::s: {one, two, three} Print using custom closure as a projection: {1:one, 2:two, 3:three}
[编辑] 另请参见
(C++20) |
返回类型参数不变 (类模板) |