flonk flonk - 3 months ago 12
C++ Question

Designing two equivalent member functions returning a const and a non-const pointer-to-member, respectively

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.

Answer

I want to premise the answer it could depend on the particular context (for example the length-code of the functions, returned type, etc...).

In general, for my experiences, the most practical, even if maybe a little bit ugly, solution is the const cast operator.

Just to implement the const method and get it with a conversion in the non-const other method. Something like:

const int* A::f_const() const {
  return &(this->some_container[some_index]);
}

int* A::f() {
  return const_cast<int*>(f_const());
}

This is usually safe because you're the designer of the class itself.