Getting around const'ness of a C++ method in derived class
I have to use a framework which defines an important hook method as const, like this
class FrameworkClass {
...
virtual void OnEventA(unsigned value) const;
...
}
In my derived cla开发者_StackOverflowss I have to save the value that I get through the hook
class MyClass: public FrameworkClass
{
...
virtual void OnEventA(unsigned value) const { savedValue = value; } // error!
private:
unsigned savedValue;
}
Unfortunately I can't change the framework.
Is there a good way to get around the const'ness of the hook method ?
Make the variable mutable:
mutable unsigned savedValue;
mutable
is too "broad" workaround because affects methods that use const'ness correctly. to workaround inappropriate const'ness there's const_cast
:
class MyClass: public FrameworkClass
{
...
virtual void OnEventA(unsigned value) const { const_cast<MyClass*>(this)->savedValue = value; } // error!
private:
unsigned savedValue;
}
精彩评论