namespace cpp {}

C++ lernen, kennen, anwenden

Benutzer-Werkzeuge

Webseiten-Werkzeuge


kennen:lib:mem_fn
no way to compare when less than two revisions

Unterschiede

Hier werden die Unterschiede zwischen zwei Versionen angezeigt.


kennen:lib:mem_fn [2019-11-20 15:50] (aktuell) – angelegt - Externe Bearbeitung 127.0.0.1
Zeile 1: Zeile 1:
 +====== mem_fn() ======
 +''#include'' [[..:include:functional]]
 +
 +<code cpp>
 +template<class R, class T>
 +unspecified mem_fn(R T::* pm)
 +</code>
 + Erzeugt ein Funktionsobjekt für eine Methode ''f'', 
 + die über einen ''T''-Objektzeiger aufgerufen wird.
 +
 +==== Parameter ====
 +| ''f'' | Name einer Methode |
 +==== Ergebnis ====
 +Rückgabewert: ein [[..:begriffe#Funktor]].
 +
 +==== Siehe auch ====
 +[[bind]],
 +[[..:stl#Funktionsadapter]],
 +[[..:funktion#anonyme_funktionen|Lambda-Ausdruck]].
 +
 +
 +==== Beispiel ====
 +<code cpp mem_fn.cpp>
 +#include <functional>
 +#include <iostream>
 +#include <string>
 +
 +int main()
 +{
 +  auto f = std::mem_fn(&std::string::size);
 +
 +  std::string woerter[] = { "Ein", "Test" };
 +  for(auto e : woerter)
 +  {
 +    std::cout << e << " : " << f(e) << '\n';
 +  }
 +  
 +  // === überladene Methoden mit cast spezifiziert:
 +  
 +  // std::string& (std::string::*member)(const std::string&)>
 +  auto member = 
 +    static_cast<std::string& (std::string::*)(const std::string&)>(&std::string::append);
 +
 +  auto fn = std::mem_fn(member);
 +
 +  // std::function<std::string&(std::string&)> 
 +  auto binder = std::bind(fn, std::placeholders::_1, " and bind");
 +
 +  // === bind() auch ohne mem_fn() möglich:
 +  
 +  // std::function<std::string&(std::string&, const std::string&)> 
 +  auto binder2 = std::bind(member, std::placeholders::_1, std::placeholders::_2);
 +
 +  // === oder Lambda-Ausdruck:
 +
 +  auto lambda = [](std::string& s, const std::string& appendix) 
 +    -> std::string& 
 +    {
 +      return s.append(appendix);
 +    };
 +  // trailing return type needed here, otherwise std::function<> cannot resolve
 +
 +  // std::function<std::string&(std::string&, const std::string&)> 
 +  auto f = std::function<std::string&(std::string&, const std::string&)>(lambda);
 +
 +  std::string s = "Hello";
 +  (s.*member)(" world");
 +  fn(s, " of mem_fn");
 +  binder(s);
 +  binder2(s, " with placeholders");
 +  lambda(s, " or lambda");
 +  f(s, " as function");
 +
 +  std::cout << s << '\n';
 +}
 +</code>
 +
  
kennen/lib/mem_fn.txt · Zuletzt geändert: 2019-11-20 15:50 von 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki