std::identity
| Défini dans l'en-tête <functional>
|
||
struct identity;
|
(depuis C++20) | |
std::identity est un type d'objet fonction dont le operator() renvoie son argument inchangé.
Types membres
| Type | Définition |
is_transparent
|
unspecified |
Fonctions membres
|
operator()
|
retourne l'argument inchangé
(fonction membre publique) |
std::identity:: operator()
|
template
<
class
T
>
constexpr T && operator ( ) ( T && t ) const noexcept ; |
||
Retourne std:: forward < T > ( t ) .
Paramètres
| t | - | argument à retourner |
Valeur de retour
std:: forward < T > ( t ) .
Notes
std::identity
sert de projection par défaut dans les
algorithmes contraints
. Son utilisation directe n'est généralement pas nécessaire.
Exemple
#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 << '}'; } }; // Un afficheur de plage capable d'afficher les éléments projetés (modifiés) d'une plage. template<std::ranges::input_range R, typename Projection = std::identity> //<- Notez la projection par défaut 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("Affichage avec std::identity comme projection : ", v); print("Projection de Pair::n : ", v, &Pair::n); print("Projection de Pair::s : ", v, &Pair::s); print("Affichage avec une fermeture personnalisée comme projection : ", v, [](Pair const& p) { return std::to_string(p.n) + ':' + p.s; }); }
Sortie :
Affichage avec std::identity comme projection : {{1, one}, {2, two}, {3, three}}
Projection de Pair::n : {1, 2, 3}
Projection de Pair::s : {one, two, three}
Affichage avec une fermeture personnalisée comme projection : {1:one, 2:two, 3:three}
Voir aussi
|
(C++20)
|
retourne l'argument de type inchangé
(modèle de classe) |