开发者

Getting around const'ness of a C++ method in derived class

开发者 https://www.devze.com 2023-02-10 05:01 出处:网络
I have to use a framework which defines an important hook method as const, like this class FrameworkClass {

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消