Boost logo

Boost :

From: Daniel Gutson (danielgutson_at_[hidden])
Date: 2007-09-25 13:37:24


Hi Boost community,
  Despite I´m a newby using Boost, I wanted to ask some users about a
very old yet useful idea: the continuations.

As an experiment, I made an extremely simple example of how a
continuation could look like in C++, and now I was wondering either
how can Boost and this concept make benefit of each other: in the case
of the concept, what´s the best way to implement continuations using
boost, and in the case of boost, whether a new library or extension to
functional can be extended to support this feature.

The design goals I setted are:
   - avoid usage of stack and recursion
   - basic design principles (such as Law of Demeter) compliancy
   - avoid complex iterative functions for implementing iterative algorithms
   - provide both a standard way of implementing this, and a
platform-specific calling convention with compiler hacks
   - maximize simplicity

In order to test the idea, I made a very simple test implementing a
classic factorial using continuations.

The ´library´ part of my code is:

template <class INFO>
class Caller
{
public:
   typedef void Continuation(Caller<INFO>& caller, INFO& info);

private:

   INFO& info;
   Continuation* next;

public:
   Caller(Continuation* ini, INFO& init_info)
       : info(init_info), next(ini)
   {}

   void operator()()
   {
       while (next != NULL)
           next(*this, info);
   }

   void stop_calling()
   {
       next = NULL;
   }

   void set_next(Continuation* cont)
   {
       next = cont;
   }

};

/////////////////////////// And the factorial example is: ////////////

struct Info
{
   int level;
   int result;
};

void fun2(Caller<Info>& caller, Info& info)
{

   if (info.level > 0)
   {
       info.result *= info.level;
       info.level--;
   }
   else
       caller.stop_calling();
}

void fun1(Caller<Info>& caller, Info& info)
{
   info.result = 1;
   info.level = 5;
   caller.set_next(fun2);
}

int main()
{
   Info info;
   Caller<Info> c(fun1, info);

   c();

   cout << info.result << endl;
}

Now the three questions:
  - how can this be best implemented using boost?
  - is this of enough interest so to be an enhancement of functional,
or even a new library?
  - could Boost provide a mix of calling-convention plus library
implementation (compiler-specific) so the above example could be even
simpler? I can think of some g++ hacks.

Thanks, and my apologies if this isn´t the proper place to post this.

Sincerely,
   Daniel Gutson.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk