简体   繁体   中英

How do I 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 & 4) insist that instance should be non-const? Would that const_cast cause issues?

FYI: instance` is not necessarily const, I just don't want a callee to mess with it.

What is happening here?

The error is in the line before. Change the typedef to

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

To make it a pointer to a const member function type.

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

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

A member-function pointer in particular is actually just a special case of a member-pointer in general. For a const member function, the function type of the member function is different than for a non-const member function.That is why the types have to match.

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

Here you are defining a pointer to a function which might modify its object.

MemFunc func=&MyClass::Dummy;

Here you are assigning a function which won't change it's object to such a pointer. This is legal, since not changing is a subset of might change .

(instance->*func)();

Here you are trying to call a function which might change its object, using an object which cannot be changed.

You will need to change the definition of MemFunc

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