Boost logo

Boost :

Subject: [boost] [local_function] inheriting local functions?
From: Lorenzo Caminiti (lorcaminiti_at_[hidden])
Date: 2010-09-12 15:46:54


Hello all,

Local functions are essentially implemented as member functions of
local classes. These member functions do not have to be static and
they could be virtual allowing for a local function to override one
another.

However, I cannot understand if this overriding "feature" has any
value at all... Have you ever used anything similar? Can you think of
a use case for it?

Consider the following example where the local function `lfn_deriv` is
"derived" from the local function `lfn_base`:

#include <iostream>

void f(double x) {
    struct lfn_base {
        lfn_base(double const& bound_x): x(bound_x) {}
        virtual int operator()(int y) {
            return x + y;
        }
    private:
        double const& x;
    } base(x);

    struct lfn_deriv: lfn_base { // inherits from `lfn_base`
        lfn_deriv(double const& bound_x): lfn_base(bound_x), x(bound_x) {}
        virtual int operator()(int y) {
            if (y < 0) return x * y;
            return lfn_base::operator()(y); // Call the base implementation.
        }
    private:
        double const& x;
    } deriv(x);

    std::cout << base(10) << std::endl; // prints `12`
    std::cout << deriv(10) << std::endl; // prints `12`
    std::cout << deriv(-10) << std::endl; // prints `-20`
}

int main() {
    f(2);
    return 0;
}

Do you have any use for code like this where the local function body is virtual?

The only reason I can think of to do something like this is to allow
`lfn_deriv` to call `lfn_base`. But in that case I rather pass (or
bind) the `lfn_base` functor to the definition of `lfn_deriv`...

--
Lorenzo

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