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

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

    Here's a C++17 version of the template static helper function, with and optional SFINAE test.

    #include 
    
    #define REQUIRES(...)         class = std::enable_if_t<(__VA_ARGS__)>
    #define REQUIRES_CV_OF(A,B)   REQUIRES( std::is_same_v< std::remove_cv_t< A >, B > )
    
    class Foobar {
    private:
        int something;
    
        template
        static auto& _getSomething(FOOBAR& self, int index) {
            // big, non-trivial chunk of code...
            return self.something;
        }
    
    public:
        auto& getSomething(int index)       { return _getSomething(*this, index); }
        auto& getSomething(int index) const { return _getSomething(*this, index); }
    };
    

    Full version: https://godbolt.org/z/mMK4r3

提交回复
热议问题