I need to call a const function from a non-const object. See example
struct IProcess {
virtual bool doSomeWork() const = 0L;
};
class Foo : public IProcess {
virtual bool doSomeWork() const {
...
}
};
class Bar
{
public:
const IProcess& getProcess() const {return ...;}
IProcess& getProcess() {return ...;}
void doOtherWork {
getProcess().doSomeWork();
}
};
Calling
getProcess().doSomeWork();
will always results in a call to
IProcess& getProcess()
Is there another way to call
const IProcess& getProcess() const
from a non constant member function?
I have so far used
const_cast<const Bar*>(this)->getProcess().doSomeWork();
which does the trick but seems overly complicated.
Edit: I should mention that code is being refactored and eventually only one function will remain.
const IProcess& getProcess() const
However, currently there is a side effect and the const call may return a different instance of IProcess some of the time.
Please keep on topic.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…