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

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

    Didn't find what I was looking for, so I rolled a couple of my own...

    This one is a little wordy, but has the advantage of handling many overloaded methods of the same name (and return type) all at once:

    struct C {
      int x[10];
    
      int const* getp() const { return x; }
      int const* getp(int i) const { return &x[i]; }
      int const* getp(int* p) const { return &x[*p]; }
    
      int const& getr() const { return x[0]; }
      int const& getr(int i) const { return x[i]; }
      int const& getr(int* p) const { return x[*p]; }
    
      template
      auto* getp(Ts... args) {
        auto const* p = this;
        return const_cast(p->getp(args...));
      }
    
      template
      auto& getr(Ts... args) {
        auto const* p = this;
        return const_cast(p->getr(args...));
      }
    };
    

    If you have only one const method per name, but still plenty of methods to duplicate, then you might prefer this:

      template
      auto* pwrap(T const* (C::*f)(Ts...) const, Ts... args) {
        return const_cast((this->*f)(args...));
      }
    
      int* getp_i(int i) { return pwrap(&C::getp_i, i); }
      int* getp_p(int* p) { return pwrap(&C::getp_p, p); }
    

    Unfortunately this breaks down as soon as you start overloading the name (the function pointer argument's argument list seems to be unresolved at that point, so it can't find a match for the function argument). Although you can template your way out of that, too:

      template
      auto* getp(Ts... args) { return pwrap(&C::getp, args...); }
    

    But reference arguments to the const method fail to match against the apparently by-value arguments to the template and it breaks. Not sure why.Here's why.

提交回复
热议问题