名稱空間
變體
操作

std::identity

來自 cppreference.com
 
 
 
函式物件
函式呼叫
(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;
(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}

[編輯] 參閱

返回不變的型別引數
(類模板) [編輯]