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

后端 未结 19 1669
天涯浪人
天涯浪人 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 00:56

    You could also solve this with templates. This solution is slightly ugly (but the ugliness is hidden in the .cpp file) but it does provide compiler checking of constness, and no code duplication.

    .h file:

    #include 
    
    class Z
    {
        // details
    };
    
    class X
    {
        std::vector vecZ;
    
    public:
        const std::vector& GetVector() const { return vecZ; }
        std::vector& GetVector() { return vecZ; }
    
        Z& GetZ( size_t index );
        const Z& GetZ( size_t index ) const;
    };
    

    .cpp file:

    #include "constnonconst.h"
    
    template< class ParentPtr, class Child >
    Child& GetZImpl( ParentPtr parent, size_t index )
    {
        // ... massive amounts of code ...
    
        // Note you may only use methods of X here that are
        // available in both const and non-const varieties.
    
        Child& ret = parent->GetVector()[index];
    
        // ... even more code ...
    
        return ret;
    }
    
    Z& X::GetZ( size_t index )
    {
        return GetZImpl< X*, Z >( this, index );
    }
    
    const Z& X::GetZ( size_t index ) const
    {
        return GetZImpl< const X*, const Z >( this, index );
    }
    

    The main disadvantage I can see is that because all the complex implementation of the method is in a global function, you either need to get hold of the members of X using public methods like GetVector() above (of which there always need to be a const and non-const version) or you could make this function a friend. But I don't like friends.

    [Edit: removed unneeded include of cstdio added during testing.]

提交回复
热议问题