【问题标题】:How to handle const/non const combination of getters without duplicate code? [duplicate]如何在没有重复代码的情况下处理 getter 的 const/non const 组合? [复制]
【发布时间】:2020-04-07 00:21:59
【问题描述】:

假设我有一个结构,它有一个名称和一些与之关联的值:

struct Season {
  std::string name;
  // Mean temperature over the season
  double meanTemperature;
  // Days since the start of year when it's strongest
  float strongestAt;
  // Fraction of a year it applies to, compared to other seasons
  float yearFraction;
}

这个类描述了每年的一个季节。假设我有一个它们的集合,它填充了一整年:

// made up method that is supposed to find a season (I don't use it in real code)
int findIndex(const std::vector<Season>& in, std::function<bool(const Season&)>);
class SeasonCollection
{
public:
  const Season* GetSeason(const std::string& name) const
  {
    const int index = findIndex(_seasons, [name](const Season& s) { return s.seasonName == name; });
    return index != -1 ? &_seasons[index] : nullptr;
  }
  Season* GetSeason(const std::string& name)
  {
    const int index = findIndex(_seasons, [name](const Season& s) { return s.seasonName == name; });
    return index != -1 ? &_seasons[index] : nullptr;
  }
private:
  //! Settings for seasons
  std::vector<Season> _seasons;
};

在该集合中,您可以看到我需要同时获取 const Season* 和 Season*。这是因为在某些情况下,集合是只读的,而在另一些情况下,它是可写的。

还有其他获取季节的方法,例如一年中的某一天(例如圣诞节24.12)。我想为每种获取方法都有一个const getter,但我也不想复制粘贴每个方法,只需添加const。

最好的方法是什么?

【问题讨论】:

    标签: c++ c++11 constants code-reuse


    【解决方案1】:

    我不想这么说,但是const_cast。你要做的是创建并调用const getter,然后删除它返回的const,因为你知道你在非常量 getter 内的非常量对象中。看起来像

      const Season* GetSeason(const std::string& name) const
      {
        const int index = findIndex(_seasons, [name](const Season& s) { return s.seasonName == name; });
        return index != -1 ? &_seasons[index] : nullptr;
      }
      Season* GetSeason(const std::string& name)
      {
        return const_cast<Season*>(const_cast<SeasonCollection const *>(this)->GetSeason(name));
        //     ^ remove the const^ ^ add const to call the const getter     ^^call const getter^
      }
    

    【讨论】:

    • 我希望这不是唯一的答案。
    • @TomášZato-ReinstateMonica 为什么会这样?像goto、const_cast 实际上有有效的用例,这就是其中之一。
    【解决方案2】:

    来自 Scott Meyers 的书,Effective C++,第 4 项:

    当 const 和 non-const 成员函数本质上相同时 实现,代码重复可以通过有 非 const 版本调用 const 版本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-25
      • 2011-08-09
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多