Как удалить дублирование кода между похожими константными и неконстантными функциями-членами?

Допустим, у меня есть следующееclass X где я хочу вернуть доступ к внутреннему члену:

class Z
{
    // details
};

class X
{
    std::vector<Z> vecZ;

public:
    Z& Z(size_t index)
    {
        // massive amounts of code for validating index

        Z& ret = vecZ[index];

        // even more code for determining that the Z instance
        // at index is *exactly* the right sort of Z (a process
        // which involves calculating leap years in which
        // religious holidays fall on Tuesdays for
        // the next thousand years or so)

        return ret;
    }
    const Z& Z(size_t index) const
    {
        // identical to non-const X::Z(), except printed in
        // a lighter shade of gray since
        // we're running low on toner by this point
    }
};

Две функции-членаX::Z() а такжеX::Z() const иметь одинаковый код внутри фигурных скобок. Это дублированный кодand can cause maintenance problems for long functions with complex logic.

Есть ли способ избежать этого дублирования кода?

Ответы на вопрос(15)

Ваш ответ на вопрос