How to call a member function pointer using a pointer to a constant object?

Here is an example of what I want to accomplish and how:

class MyClass
{
     public: 
         void Dummy() const{}

};
typedef void (MyClass::*MemFunc)();

void  (const MyClass * instance)
{
     MemFunc func=&MyClass::Dummy;
     // (instance->*func)(); //gives an error
         (const_cast<MyClass *>instance->*func)(); // works
}

Why do compilers (gcc 3 and 4) insist that the instance be non-constant? Could there be a problem with const_cast?

FYI: instance` is not necessarily const, I just don't want the caller to call with it.

What's going on here?

+3
source share
2 answers

Error in line before. Change typedef to

typedef void (MyClass::*MemFunc)() const;

Make this a pointer to a const member function type.

The difference may be more clear when considering this code and how it works:

typedef void FunctionType() const;
typedef FunctionType MyClass::*MemFunc;

-, , - . - const - --const-. .

+7

typedef void (MyClass:: * MemFunc)();

, .

MemFunc func = & MyClass:: Dummy;

, . , .

( → * FUNC)();

, , , .

MemFunc

0

Source: https://habr.com/ru/post/1704590/


All Articles