|
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