Boost logo

Boost Users :

Subject: Re: [Boost-users] self-referential boost functions
From: Philipp Moeller (philipp.moeller_at_[hidden])
Date: 2012-06-28 12:31:20


Adam Crain <jadamcrain_at_[hidden]> writes:

> Inquiring as to whether this is possible or if there is a better pattern
> for simulating this behavior...
>
> Is it possible for boost::function to be self referential? I.e. how do I
> simulate behavior like the following:
>
> typedef boost::function<Func (int)> Func;
>
> A function that does something mutable and then returns the next function
> to be called or an empty function.

Boost.Function still requires static typing on the return type and that
type depends on some runtime variable, so you cannot statically type it.

What might work:

#include <boost/any.hpp>
#include <boost/function.hpp>

boost::any foo(int i) {
  if(i == 0) return boost::any();
  else return boost::function<boost::any(int)>(&foo);
}

int main()
{
  boost::function< boost::any(int) > f = &foo;
  auto x = f(3);
  if(!x.empty()) {
     // maybe unsafe any cast?
    f = boost::any_cast<boost::function< boost::any(int) > >(x);
  } else {
    // hit end
  }

  return 0;
}

but I think that is possibly slower than you want.

HTH,
Philipp


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net