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

后端 未结 19 1726
天涯浪人
天涯浪人 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:07

    Nice question and nice answers. I have another solution, that uses no casts:

    class X {
    
    private:
    
        std::vector v;
    
        template
        static auto get(InstanceType& instance, std::size_t i) -> decltype(instance.get(i)) {
            // massive amounts of code for validating index
            // the instance variable has to be used to access class members
            return instance.v[i];
        }
    
    public:
    
        const Z& get(std::size_t i) const {
            return get(*this, i);
        }
    
        Z& get(std::size_t i) {
            return get(*this, i);
        }
    
    };
    

    However, it has the ugliness of requiring a static member and the need of using the instance variable inside it.

    I did not consider all the possible (negative) implications of this solution. Please let me know if any.

提交回复
热议问题