简体   繁体   中英

Pointer to member function in virtual function

Is it possible to call a member function from an overriden virtual function ? Compiler tells me that the member function has no address ( lvalue required as unary '&' operand ). I would like to do something like:

class Virtual
{
public:
    virtual void f() = 0;
};

class Real : public Virtual
{
public:
    void f() override { g(&Real::h()); }

private:
    void g(bool (Real::*p)() );
    bool h();
};

However, inside f() , any member pointer statement is invalid ( &Real::h() , std::mem_fn(&Real::h()) , std::function<bool<void>(h) etc) because it does not consider it an l-value (namely, it does not have an address). I think the reason is that virtual functions are evaluated at run time and that this member pointer must be evaluated at compilation time. Then, is there any alternative?

Thank you!

The error message already gives a good hint on what is wrong here:

<source>:10:27: error: cannot take the address of an rvalue of type 'bool'
    void f() override { g(&Real::h()); }
                          ^~~~~~~~~~

Real::h() is bool . Correct syntax to get a pointer to the member function is

    void f() override { g(&Real::h); } 
                           //     ^  -------- no () !!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM