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

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

    I did this for a friend who rightfully justified the use of const_cast... not knowing about it I probably would have done something like this (not really elegant) :

    #include 
    
    class MyClass
    {
    
    public:
    
        int getI()
        {
            std::cout << "non-const getter" << std::endl;
            return privateGetI(*this);
        }
    
        const int getI() const
        {
            std::cout << "const getter" << std::endl;
            return privateGetI(*this);
        }
    
    private:
    
        template 
        static T privateGetI(C c)
        {
            //do my stuff
            return c._i;
        }
    
        int _i;
    };
    
    int main()
    {
        const MyClass myConstClass = MyClass();
        myConstClass.getI();
    
        MyClass myNonConstClass;
        myNonConstClass.getI();
    
        return 0;
    }
    

提交回复
热议问题