C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Derived class's function invokes base class's function

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Sat, 16 Apr 2022 09:07:16 +0100
On 4/16/22, Thiago Macieira via Std-Proposals
<std-proposals_at_[hidden]> wrote:

> How about this use-case:
>
> bool Klass::func(int &r)
> {
> if (this->Base1::func(r))
> return true;
> if (this->Base2::func2(r))
> return true;
> r = 3;
> return false;
> }


I'm considering presenting an array of function pointers to
programmers so that they have that kind of control. Here's an
approximation of how my 'precompiler' would do it:

#include <array>

class Laser {
public:
    virtual bool Trigger(void)
    {
        return true;
    }
};

class Laser_Nitrogen : virtual public Laser {
public:
    bool Trigger(void) override
    {
        static std::array<bool (Laser::*)(void), 1u> const methods {
&Laser::Trigger };

        for ( auto const &method : methods )
        {
            (this->*method)();
        }

        return false;
    }
};

class Laser_PicoSecond : virtual public Laser {
public:
    bool Trigger(void) override
    {
        static std::array<bool (Laser::*)(void), 1u> const methods {
&Laser::Trigger };

        return true;
    }
};

class Laser_NitrogenPicoSecond : public Laser_Nitrogen, public
Laser_PicoSecond {
public:
    bool Trigger(void) override
    {
        static std::array<bool (Laser::*)(void), 3u> const methods {
            &Laser::Trigger,
            static_cast<bool (Laser::*)(void)>(&Laser_Nitrogen::Trigger),
            static_cast<bool (Laser::*)(void)>(&Laser_PicoSecond::Trigger)
        };

        for ( auto const &method : methods )
        {
            if ( (this->*method)() ) return true;
        }

        return false;
    }
};


This sample experimental code has two problems:

(1) It invokes the base method twice on the same object
(2) It doesn't compile because of casting to a virtual base

but I think you see the idea of what I'm trying to do.

Received on 2022-04-16 08:07:18