You have to call the function on a const pointer. For this, I recommend to create a local pointer variable:
const auto *c = this;
c->fun(); // calls fun() const
fun(); // calls fun()
Live Demo
If you need that often, and/or if you don't want to use a local variable, you could also introduce a private helper function which returns a const this pointer:
const MyQuestion *const_this() const {
return this;
}
and then call fun
like this:
const_this()->fun(); // calls fun() const
fun(); // calls fun()
Live Demo
Yet another option is to write a make_const
function which performs a cast to a const pointer without the need to mention the class name (it's basically a static_cast
to a const pointer of a deduced type):
template <typename T>
const T* make_const(T *ptr) {
return ptr;
}
and then call fun
like this:
make_const(this)->fun(); // calls fun() const
fun(); // calls fun()
Live Demo
For the sake of argument (I don't recommend the following), combining with the suggestion above, you could also introduce a global macro which expands to make_const(this)
:
#define const_this make_const(this)
and then call fun
like this:
const_this->fun(); // calls fun() const
fun(); // calls fun()
Live Demo