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

后端 未结 19 1729
天涯浪人
天涯浪人 2020-11-22 00:30

Let\'s say I have the following class X where I want to return access to an internal member:

class Z
{
    // details
};

class X
{
    std::vec         


        
19条回答
  •  遥遥无期
    2020-11-22 01:01

    I'd suggest a private helper static function template, like this:

    class X
    {
        std::vector vecZ;
    
        // ReturnType is explicitly 'Z&' or 'const Z&'
        // ThisType is deduced to be 'X' or 'const X'
        template 
        static ReturnType Z_impl(ThisType& self, size_t index)
        {
            // massive amounts of code for validating index
            ReturnType ret = self.vecZ[index];
            // even more code for determining, blah, blah...
            return ret;
        }
    
    public:
        Z& Z(size_t index)
        {
            return Z_impl(*this, index);
        }
        const Z& Z(size_t index) const
        {
            return Z_impl(*this, index);
        }
    };
    

提交回复
热议问题