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

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

    For those (like me) who

    • use c++17
    • want to add the least amount of boilerplate/repetition and
    • don't mind using macros (while waiting for meta-classes...),

    here is another take:

    #include 
    #include 
    
    template  struct NonConst;
    template  struct NonConst {using type = T&;};
    template  struct NonConst {using type = T*;};
    
    #define NON_CONST(func)                                                     \
        template  auto func(T&&... a)                            \
            -> typename NonConst(a)...))>::type   \
        {                                                                       \
            return const_cast(a)...))>(           \
                std::as_const(*this).func(std::forward(a)...));              \
        }
    

    It is basically a mix of the answers from @Pait, @DavidStone and @sh1 (EDIT: and an improvement from @cdhowie). What it adds to the table is that you get away with only one extra line of code which simply names the function (but no argument or return type duplication):

    class X
    {
        const Z& get(size_t index) const { ... }
        NON_CONST(get)
    };
    

    Note: gcc fails to compile this prior to 8.1, clang-5 and upwards as well as MSVC-19 are happy (according to the compiler explorer).

提交回复
热议问题