std::identity
From cppreference.com
< cpp | utility | functional
| ヘッダ <functional> で定義 |
||
| struct identity; |
(C++20以降) | |
std::identity は、その operator() が引数を変更せずに返す関数オブジェクト型です。
目次 |
[編集] メンバ型
| 型 | 定義 |
is_transparent
|
unspecified |
[編集] メンバ関数
| operator() |
引数を変更せずに返す (public member function) |
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) |
型引数を変更せずに返す (クラステンプレート) |