Namespaces
Variants

std::identity

ja.cppreference.net より
 
 
ユーティリティライブラリ
言語サポート
型サポート (基本型、RTTI)
ライブラリ機能テストマクロ (C++20)
プログラムユーティリティ
可変引数関数
コルーチンサポート (C++20)
契約サポート (C++26)
三方比較
(C++20)
(C++20)(C++20)(C++20)    
(C++20)(C++20)(C++20)

汎用ユーティリティ
関係演算子 (C++20で非推奨)
整数比較関数
(C++20)(C++20)(C++20)    
(C++20)
swap および 型操作
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
共通語彙型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)



 
関数オブジェクト
関数呼び出し
(C++17)(C++23)
恒等関数オブジェクト
(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 unspecified

メンバー関数

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; });
}

出力:

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}

関連項目

型引数を変更せずに返す
(クラステンプレート)