开发者

How to code Const and Mutable overloads?

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 开发者_C百科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));
    }


Use the following trick (which I originally got from Scott Meyers' book Effective C++):

int& myClass::getData()
{
    // This is safe because we know from out here
    // that the return value isn't really const
    return const_cast<int&>(const_cast<const myClass&>(*this).getData());
}

const int& myData::getData() const
{
    return data;
}

Obviously for a short function like this, you may find it easier just to duplicate code, but this idiom is useful when you have a longer function (like vector<T>::at or it is subject to lots of changes.


Providing a function like:

int& myClass::getData()
{
    return data;
}

is probably wrong - you might as well make 'data' public. And the second should be written as:

int myData::getData() const
{
   return data;
}


The reason the Standard Library functions you quote duplicate the code is that Standard Library functions need to be as performant as possible. Putting a call to another function in there (as others have correctly suggested doing) might screw that. But your code is probably under much less stringent performance constraints, so you should use common code, where possible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜