문제

Here is my problem. I made a class with a member function declared as const that uses an external function that I cannot modify (declared in someone else's code) and that is not declared const. More precisely

Someone else's code

class B {
public:
    void foo();
};

My code

class A : public B {
public:
    void bar() const {
        this->foo();
    }
};

I know that for member data we can force const-correctness by using mutable or const_cast. How can I 'hack' foo such that my compiler understands that I would like to use it as if it was const even if it is not declared in someone else's code ?

도움이 되었습니까?

해결책

  1. Dont do that.

  2. Don't do it like this:

Example:

class A : public B { 
public: 
    void bar() const { 
        const_cast<B*>(static_cast<const B*>(this))->foo();
    } 
}; 

Edit: The valid use-case for this is if:

  1. The function B::foo() doesn't modify state, and could have been declared const, but...
  2. The person who wrote B::foo() forgot to declare it const, and...
  3. You can't change it because it will break something you don't control.

In theory this cannot happen but in practice it sometimes does.

The better answer, as the other answerers have correctly said, is to have B::foo() fixed, or to provide an alternate function which does the same thing is declared const.

다른 팁

Just make your function non-const. That is the correct way to do it.

This makes clear that you will be modifying your state.

Either make B::foo() const, or make A::bar() non-const. One of the two.

You can declare bar() as follows:

void bar() const {
    B *that = (B *) this;
    that->foo();
}

Not sure about any unintended side affects.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top