dimanche 24 avril 2016

Calling non-const member function pointer from const member function

I have the following code:

class MyClass;
typedef void(MyClass::*func_ptr)();
class MyClass
{
public:

MyClass()
{
    f = &MyFunc1;
}

void MyFunc1()
{
    // ...
}

void MyFunc2() const
{
    (this->*f)();
}

func_ptr f;

};

If I try to compile, it fails because of MyFunc2() which is a const method trying to call the function pointer of type func_ptr which is non-const.

I'm trying to figure out the best way to cast this. I can use a standard C style cast:

    typedef void(MyClass::*func_ptr2)() const;
    func_ptr2 f2 = (func_ptr2)f;
    (this->*f2)();

But I'd prefer to use a C++ cast (i.e. static_cast, reinterpret_cast, or const_cast). I got this to compile with reinterpret_cast but I can't get it working with const_cast. I thought const_cast was mean't to be used for this case? Also, is there a cleaner way to do this without having to create another typedef?

Aucun commentaire:

Enregistrer un commentaire