如何避免const版本函数的代码重复

How to avoid code duplication for const versions of functions

本文关键字:代码 函数 何避免 const 版本      更新时间:2023-10-16
  pointer operator->()
  {
    return ptr_+buffer_position_;
  }
  const_pointer operator->() const
  {
    return ptr_+buffer_position_;
  }

所以const重载返回一个const指针(耶),但这两个函数做同样的事情(嘘)如何避免代码重复和随后的拷贝传递,同时仍然保持const正确性?

(我特别关注c++ 98…尽管c++ 11的答案会显得有些教化,因为我怀疑他们已经解决了这个问题)

如果您不使用c++11:

你可以试试:

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