命名空间
变体
操作

std::identity

来自 cppreference.cn
< cpp‎ | utility‎ | functional
 
 
 
函数对象
函数调用
(C++17)(C++23)
恒等函数对象
identity
(C++20)
透明运算符包装器
(C++14)
(C++14)
(C++14)
(C++14)  
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)

旧式绑定器和适配器
(直到 C++17*)
(直到 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;
(since C++20)

std::identity 是一个函数对象类型,其 operator() 返回其参数,不做任何更改。

目录

[edit] 成员类型

类型 定义
is_transparent 未指定

[edit] 成员函数

operator()
返回未更改的参数
(公共成员函数)

std::identity::operator()

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

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

参数

t - 要返回的参数

返回值

std::forward<T>(t).

[edit] 注意

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

[edit] 示例

#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}

[edit] 参见

返回未更改的类型参数
(类模板) [编辑]