Subject: Re: [boost] [local_function] any interest in a LocalFunction library?
From: Lorenzo Caminiti (lorcaminiti_at_[hidden])
Date: 2010-09-15 13:55:15
On Wed, Sep 15, 2010 at 10:56 AM, Lorenzo Caminiti
<lorcaminiti_at_[hidden]> wrote:
>.)
As of right now, local function will be implemented more or less using
the following skeleton code (many thanks to John Bytheway for refining
my global base functors trick):
#include <iostream>
#include <algorithm>
#include <vector>
// Must be global type so lfn inheriting from this can be passed as tparam.
template<typename F> struct lfn_ftor_base {};
template<typename R, typename A1> struct lfn_ftor_base<R (A1)>
// Abstract so never returns R (R could be void, have no default ctor, etc).
{ virtual R operator()(A1) = 0; };
// Wrap lfn functor ref in global type so it can be passed as tparm.
template<typename F> struct lfn_ftor_ref {};
template<typename R, typename A1> struct lfn_ftor_ref<R (A1)> {
typedef R (f_type)(A1);
explicit lfn_ftor_ref(lfn_ftor_base<f_type>& ftor): ftor_(ftor) {}
inline R operator()(A1 a1) { return ftor_(a1); }
private:
lfn_ftor_base<f_type>& ftor_;
};
int main () {
double x = 5.6;
// BOOST_LOCAL_FUNCTION(
// (inline) (void) (lfn)( (int)(i) (const bound)((&x)) )
// ) {
// std::cout << " " << i + x;
// if (i > 0) lfn(-i); // Recursive call.
// } BOOST_LOCAL_FUNCTION_END(lfn)
// Implementation of a local function named `lfn`.
struct lfn_ftor: lfn_ftor_base<void (int)> {
typedef void (f_type)(int);
explicit lfn_ftor(double const& x): bound_x_(x) {}
// Implement abstract base functor.
inline void operator()(int i) { lfn(i); }
private:
// Bound params hold in a member variable (this example hides all
// ScopeExit-like bound param type determination code).
double const& bound_x_;
// Member with local func name to allow recursion.
inline void lfn(int i) { body(i, bound_x_); }
// Body func cannot be static to allow recursive calls to `lfn`
// (limitation: `this` available also when `this_` should be used).
// Ultimately, bound params must be passed as func param because their
// name is not know to preprocessor (it can prefixed by `&`).
inline void body(int i, double const& x) {
std::cout << " " << i + x;
if (i > 0) lfn(-i); // Recursive call.
}
};
lfn_ftor lfn_obj(x); // x is const& bound from scope.
lfn_ftor_ref<lfn_ftor::f_type> lfn(lfn_obj);
std::vector<int> v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
std::cout << "v: ";
std::for_each(v.begin(), v.end(), lfn);
std::cout << std::endl;
return 0;
}
-- Lorenzo
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk