Lazy Ptr Proxy

LazyPtrProxy is an implementation of LazyInstantiationPattern in CeePlusPlus using FunctoidsInCpp (FC++).

This is referred to by Yannis Smaragdakis and Brian McNamara in the paper http://people.cs.umass.edu/~yannis/fc++/funoo.pdf, but is not actually in the FC++ library itself. It is in one of the examples of FC++ and full code can be found at http://people.cs.umass.edu/~yannis/fc++/FC++-clients.1.5/ecoop2b.cc .

  template <class T>
  class LazyPtrProxy {
     Fun0<T*> f;
     mutable T* p;
     void cache() const { if(!p) p = f(); }
  public:
     LazyPtrProxy( const Fun0<T*> ff ) : f(ff), p(0) {}
     template <class F> LazyPtrProxy( F ff ) : f(makeFun0(ff)), p(0) {}
     T& operator*() const { cache(); return *p; }
     T* operator->() const { cache(); return p; }
  };

The point is that the class object pointed to is not created until needed, which will delay an operation which takes time and effort until it is really needed.

Example of use - sample class

 class FF
 {
  string name_;
 public:
  FF(string name) : name_(name) 
  { 
    cout << "FF constucted " << name << endl; 
  } 
  void operator()() 
  {
    cout << "FF " << name_ << " was called" << endl;
  }
  void print() 
  { 
    cout << "FF " << name_ << " was called via print" << endl; 
  }
 };

Create pointer

   string name = "using LazyPtrProxy";
   LazyPtrProxy<FF> pff(curry(Make1<FF,string>(),name));

Usage

   (*pff)();
   (*pff).print(); // Call to a named function

--JohnFletcher


CategoryCpp CategoryObjectFunctionalPatterns CategoryFunctionalProgramming CategoryLazyPattern


EditText of this page (last edited May 8, 2014) or FindPage with title or text search