Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call nonconst member version from const [duplicate]

Possible Duplicate:
How do I remove code duplication between similar const and non-const member functions?

i have two members

A &B::GetA (int i)
{
    return *(m_C[m_AtoC[i]]);
}

const A &B::GetA (int i) const
{
    return *(m_C[m_AtoC[i]]);
}

for now i just duplicate code, but may be there exists nice way to do it. I certanly dont want to deal with type cast from const to non-const.

EDIT: So i want to call one member frm another to avoid code duplication.

like image 701
Yola Avatar asked Oct 05 '22 07:10

Yola


1 Answers

[Note the correction; sorry for getting it the wrong way round initially.]

This is an appropriate situation for using a const_cast, and it allows you to deduplicate code by forwarding the call from the non-const function to the corresponding const function:

A & B::GetA(int index) 
{
    return const_cast<A &>(static_cast<B const *>(this)->GetA(index));
}

It's important to note that this should only be done in one direction: You can implement the non-const method in terms of the constant one, but not the other way round: The constant call to GetA() gets a constant reference to the object in question, but since we have additional information that it's actually OK to mutate the object, we can safely cast away the constness from the result.

There's even a chapter on precisely this technique in Scott Meyer's Effective C++.

like image 135
Kerrek SB Avatar answered Oct 10 '22 04:10

Kerrek SB