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

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

    C++17 has updated the best answer for this question:

    T const & f() const {
        return something_complicated();
    }
    T & f() {
        return const_cast(std::as_const(*this).f());
    }
    

    This has the advantages that it:

    • Is obvious what is going on
    • Has minimal code overhead -- it fits in a single line
    • Is hard to get wrong (can only cast away volatile by accident, but volatile is a rare qualifier)

    If you want to go the full deduction route then that can be accomplished by having a helper function

    template
    constexpr T & as_mutable(T const & value) noexcept {
        return const_cast(value);
    }
    template
    constexpr T * as_mutable(T const * value) noexcept {
        return const_cast(value);
    }
    template
    constexpr T * as_mutable(T * value) noexcept {
        return value;
    }
    template
    void as_mutable(T const &&) = delete;
    

    Now you can't even mess up volatile, and the usage looks like

    decltype(auto) f() const {
        return something_complicated();
    }
    decltype(auto) f() {
        return as_mutable(std::as_const(*this).f());
    }
    

提交回复
热议问题