How to properly share a functor with state between two Loki Functors?

137 Views Asked by At

I'm using Loki::Functor for callback purposes and I wish to share a functor (object with a suitable operator() member function defined) between two callbacks. This functor needs to hold state so that both callbacks see it.

A quick test shows that constructing the Loki functor with a functor passed by value has a different result as to using the member function pointer constructor:

#include "loki/Functor.h"

struct Bar {
  int x;
  void inc() { ++x; }
  int operator()() { return x; }
  int get() { return x; }
};

Bar b;
Loki::Functor<int, Loki::NullType> f1(b);
Loki::Functor<int, Loki::NullType> f2(&b, &Bar::get);
Loki::Functor<int, Loki::NullType> f3(&b, &Bar::operator());
cout << f1() << endl;   // prints '0'
cout << f2() << endl;   // prints '0'
cout << f3() << endl;   // prints '0'
b.inc();
cout << f1() << endl;   // prints '0'
cout << f2() << endl;   // prints '1'
cout << f3() << endl;   // prints '1'

f2 demonstrates that using member function pointers and a pointer to an instance results in different behaviour to f1. Then f3 suggests itself as a possible way to share the functor between loki functors.

I believe f1 relates to the 'copy semantics' supported by Loki::Functor - a copy of the functor is made, which has a new value for x, whereas f2 and f3 do what I want - the actual instance is referenced by the loki Functor and therefore shared between them.

Therefore I'd like to know if f3 is the best way to bind the same actual instance of the functor Bar to two loki functors (f2 & f3), or is there a better/cleaner way to do it along the lines of f1 syntax?

EDIT: some might ask why am I using Loki given its age? It provides what I need in a constrained development environment, where global statics are strictly prohibited (I did have to remove the Small Object singleton from loki/Functor.h however, but that was easy). Happy to elaborate on the constraints if anyone has suggestions for alternative generalised functor libraries.

0

There are 0 best solutions below