Tom*_*ica 4 c++ code-reuse constants c++11
假设我有一个结构体,它有一个名称和一些与之关联的值:
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;
}
Run Code Online (Sandbox Code Playgroud)
本课程描述了每年的一个季节。假设我有一个它们的集合,它填充了一整年:
// 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;
};
Run Code Online (Sandbox Code Playgroud)
在该集合中,您可以看到我需要同时获取const Season*和Season*。这是因为在某些情况下,集合是只读的,而在其他情况下,它是可写的。
还有其他获取季节的方法,例如一年中的某一天(例如圣诞节24.12)。我想const为每种获取它们的方法都有一个getter,但我也不想复制粘贴它们中的每一个并添加const.
最好的方法是什么?
我不想说,但是const_cast。您所做的是创建并调用constgetter,然后删除const它返回的 ,因为您知道您位于非 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^
}
Run Code Online (Sandbox Code Playgroud)