Boost logo

Boost :

Subject: Re: [boost] [local_function] any interest in a LocalFunction library?
From: Lorenzo Caminiti (lorcaminiti_at_[hidden])
Date: 2010-08-26 15:57:32


On Sun, Aug 22, 2010 at 11:09 AM, Lorenzo Caminiti
<lorcaminiti_at_[hidden]> wrote:
> Hello all,
>
> Is there interest in a library that implement local functions for C++?

I got a first version of Boost.LocalFunction implemented. The library
uses just two macros `BOOST_LOCAL_FUNCTION()` and
`BOOST_LOCAL_FUNCTION_END()`.

The following example compiles (with both GCC and MSVC) on my
development branch:

#include <boost/local_function.hpp>
#include <iostream>

struct c {
    c(): y_(0.0) {}

    double f(double x) {
        int offset = x > 0 ? +100 : -100;

        BOOST_LOCAL_FUNCTION(
        (double) (line)( (int)(slope)
                (const bound)((&x)(offset)) (bound)((this)) )
        ) {
            // x = 0; // Correctly errors because `x` is const-bound.
            double y = slope * x + offset;
            return this_->y_ = y; // OK because `this` is not const-bound.
        } BOOST_LOCAL_FUNCTION_END(line)

        return line(2); // Usual C++ function invocation syntax.
    }

private:
    int y_;
};

int main() {
    c cc;
    std::cout << cc.f(10) << std::endl; // Outputs `120`.
    return 0;
}

Note I changed the syntax a bit:
1) There are two separate bound parameter section one for const-bounds
and another for non-const-bounds. (All local function parameters --
unbound, const-bound, non-const-bound -- are all optional.)
2) The `FUNCTION_END()` macro needs to repeat the local function name
(the complier will error if this name does not match the one specified
in the `FUNCTION()` macro). This repetition is not ideal but it allows
me to create a functor object `line` to handle the local function so
the local function can be invoked as usual by `line(2)` without using
any additional `FUNCTION_CALL()` macro.

In the example above:
a) `x` is bound and implicitly passed to the local function as a
const-reference.
b) `offset` is bound and implicitly passed to the local function as a
const-value.
c) `this` is bound and implicitly passed to the local function as a
non-const value (pointer) -- so the local function can change the
object state `y_`.

I need to write documentation, examples, and tests.

(As I mentioned, the implementation of Boost.LocalFunction parameter
binding vastly relies on Boost.ScopeExit internal mechanism to do the
same thing.)

-- 
Lorenzo

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