I seem to have this pattern occuring pretty often in my code, with two functions performing the same task apart from the constness of their parameters/returns.
int& myClass::getData()
{
return data;
}
// called for const objects
const int& myData::getData() const
{
return data;
}
This offends my sense of DRY. It's not a problem for a one-liner, but as getData() gets bigger, there's obvious duplication.
I know WHY I need both methods, but feel there should be a better way to implement it. Is there a template trick that can help, or should I have one method which calls the other casting the constness back and forth as required?
ADDED: As a more real-world example, here's a sample of typical STL vector::at() implementation:
const_reference at(size_type _Off) const
{ // subscript nonmutable sequence with checking
if (size() <= _Off)
_Xran();
return (*(begin() + _Off));
}
reference at(size_type _Off)
{ // subscript mutable sequence with checking
if (size() <= _Off)
_Xran();
return (*(begin() + _Off));
}