Boost logo

Boost :

Subject: Re: [boost] [local_function] inheriting local functions?
From: Cory Nelson (phrosty_at_[hidden])
Date: 2010-09-12 20:13:47


On Sun, Sep 12, 2010 at 12:46 PM, Lorenzo Caminiti
<lorcaminiti_at_[hidden]> wrote:
>
> 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?

I've never needed such a feature.

> 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?

Even in this example, there is no reason to make the functions
virtual. You can still call the base function without it.

--
Cory Nelson
http://int64.org

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