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

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

    Is it cheating to use the preprocessor?

    struct A {
    
        #define GETTER_CORE_CODE       \
        /* line 1 of getter code */    \
        /* line 2 of getter code */    \
        /* .....etc............. */    \
        /* line n of getter code */       
    
        // ^ NOTE: line continuation char '\' on all lines but the last
    
       B& get() {
            GETTER_CORE_CODE
       }
    
       const B& get() const {
            GETTER_CORE_CODE
       }
    
       #undef GETTER_CORE_CODE
    
    };
    

    It's not as fancy as templates or casts, but it does make your intent ("these two functions are to be identical") pretty explicit.

提交回复
热议问题