如何避免函数const版本的代码重复 [英] How to avoid code duplication for const versions of functions

查看:70
本文介绍了如何避免函数const版本的代码重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 指针运算符->(){返回ptr_ + buffer_position_;}const_pointer运算子->()const{返回ptr_ + buffer_position_;} 

因此const重载会返回const指针(是),但是两个函数都做同样的事情(boo).如何在保持const正确性的同时又避免代码重复和随后的copypasta?

(我正在专门研究C ++ 98 ...尽管C ++ 11的答案会很教学,因为我怀疑他们为解决这个问题做了一些事情.)

解决方案

如果您不使用c ++ 11:

您可以尝试以下操作:

  T类{指针运算符->(){返回const_cast< pointer>(static_cast< const T *(this)-> operator->());}const_pointer运算子->()const{返回ptr_ + buffer_position_;}}; 

  pointer operator->()
  {
    return ptr_+buffer_position_;
  }

  const_pointer operator->() const
  {
    return ptr_+buffer_position_;
  }

So the const overload returns a const pointer (yay) but the two functions do the same thing (boo) how does one avoid code duplication and the ensuing copypasta, while still maintaining const correctness?

(I'm looking at specifically C++98...though a C++11 answer would be pedagogic, as I suspect they did something to solve this problem).

解决方案

If you are not using c++11:

You can try this:

class T {
      pointer operator->()
      {
        return const_cast<pointer> (static_cast<const T*>(this)->operator->());
      }

      const_pointer operator->() const
      {
        return ptr_+buffer_position_;
      }
};

这篇关于如何避免函数const版本的代码重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆