如何处理无重复代码的吸气剂的const /非const组合?

问题描述 投票:0回答:1

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

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& 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吸气剂,但我也不想复制粘贴每种方法,而只添加const

最佳方法是什么?

c++ c++11 const code-reuse
1个回答
0
投票

我不愿意说,但是const_cast。您要做的是制作一个const吸气剂,然后删除它返回的const,因为您现在处于非常量对象中。看起来像

© www.soinside.com 2019 - 2024. All rights reserved.