I have a class A and a member function f, that returns a pointer to
some contents of the instance
int* A::f() {
// common code ...
return &(this->some_container[some_index])
}
Now, I need an analogue function, which only returns a const pointer,
i.e.
const int* A::f_const() const {
// exactly the same lengthy code ...
return &(this->some_container[some_index]);
}
Note that, as the "lengthy code" does not change the instance of A,
this also makes the function const w.r.t. the instance (the second
const statement).
My question: Now I wonder if there is some solution to avoid the code doubling, without using a third function.
On one hand, calling f inside f_const would be illegal, as f is not
const w.r.t. the owning instance. On the other hand, calling f_const
inside f would require to convert a const pointer to a non-const
pointer, which is also impossible.
Is there any elegant declaration method, to avoid code doubling?
As said, using a third function with the common functionality of f and
f_const is not an option here, as when applied for a large number of
functions, it would make the code less readable.