Boost function per functor

Rileggendo Beyond the C++ Standard Library: An Introduction to Boost di Björn Karlsson.

Parte sull'uso di function, nel capitolo undicesimo, all'interno della terza parte, dedicata ai functor e alla programmazione di più alto ordine.

Quando passiamo un functor a boost::function, in realtà ne passiamo una copia. Questo vuol dire che usiamo diverse function queste lavoreranno su differenti copie del functor.

Se vogliamo che il functor sia passato per riferimento a function dobbiamo usare un apposito wrapper di boost, e si ottiene l'effetto chiamando la funzione ref (o cref, se vogliamo una const reference) sull'oggetto.

L'esempio che segue mostra l'uso di default, con i functor copiati, e l'uso con reference, in modo che vi sia in realtà un unico functor condiviso:

#include <iostream>
#include "boost/function.hpp"

using namespace std;

class KeepingState {
int total_;
public:
KeepingState() : total_(0) {}

int operator()(int i) {
total_ += i;
return total_;
}

int total() const {
return total_;
}
};

void function04() {
KeepingState ks;
boost::function<int(int)> f1;
f1 = ks;

boost::function<int(int)> f2;
f2 = ks;

cout << "Default: functor copied" << endl;
cout << "The current total is " << f1(10) << endl;
cout << "The current total is " << f2(10) << endl;
cout << "The total is " << ks.total() << endl;

cout << "Forcing functor by reference" << endl;
f1 = boost::ref(ks);
f2 = boost::ref(ks);

cout << "The current total is " << f1(10) << endl;
cout << "The current total is " << f2(10) << endl;
cout << "The total is " << ks.total() << endl;
}

Nessun commento:

Posta un commento