ref, fonction

Construit un reference_wrapper depuis un argument.

template<class Ty>
    reference_wrapper<Ty> ref(Ty& arg);
template<class Ty>
    reference_wrapper<Ty> ref(reference_wrapper<Ty>& arg);

Valeur de retour

Une référence à arg; spécifiquement reference_wrapper<Ty>(arg).

Exemple

L'exemple suivant définit deux fonctions : une limite à une variable de chaîne, l'autre est liée à une référence de la variable chaîne calculée par un appel à ref. Lorsque la valeur de la variable change, la première fonction continue à utiliser l'ancienne valeur et la deuxième fonction utilise la nouvelle valeur.

#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <ostream>
#include <string>
#include <vector>
using namespace std;
using namespace std;
using namespace std::placeholders;

bool shorter_than(const string& l, const string& r) {
    return l.size() < r.size();
}

int main() {
    vector<string> v_original;
    v_original.push_back("tiger");
    v_original.push_back("cat");
    v_original.push_back("lion");
    v_original.push_back("cougar");

    copy(v_original.begin(), v_original.end(), ostream_iterator<string>(cout, " "));
    cout << endl;

    string s("meow");

    function<bool (const string&)> f = bind(shorter_than, _1, s);
    function<bool (const string&)> f_ref = bind(shorter_than, _1, ref(s));

    vector<string> v;

    // Remove elements that are shorter than s ("meow")

    v = v_original;
    v.erase(remove_if(v.begin(), v.end(), f), v.end());

    copy(v.begin(), v.end(), ostream_iterator<string>(cout, " "));
    cout << endl;

    // Now change the value of s.
    // f_ref, which is bound to ref(s), will use the
    // new value, while f is still bound to the old value.

    s = "kitty";

    // Remove elements that are shorter than "meow" (f is bound to old value of s)

    v = v_original;
    v.erase(remove_if(v.begin(), v.end(), f), v.end());

    copy(v.begin(), v.end(), ostream_iterator<string>(cout, " "));
    cout << endl;

    // Remove elements that are shorter than "kitty" (f_ref is bound to ref(s))

    v = v_original;
    v.erase(remove_if(v.begin(), v.end(), f_ref), v.end());

    copy(v.begin(), v.end(), ostream_iterator<string>(cout, " "));
    cout << endl;
}
  

Configuration requise

En-tête : <functional>

Espace de noms : std

Voir aussi

Référence

cref, fonction

reference_wrapper, classe