我想消除这个问题中的代码重复:
class PopulationMember
{
public:
vector<int> x_;
vector<int> y_;
}
class Population
{
vector<PopulationMember*> members_;
void doComputationforX_1(); // uses the attribute x_ of all members_
void doComputationforX_2();
void doComputationforX_3();
void doComputationforY_1(); // exactly same as doComputationforX_1, but
void doComputationforY_2(); // uses the attribute y_ of all members_
void doComputationforY_3();
EDIT: // there are also functions that use all the members_ simultaniously
double standardDeviationInX(); // computes the standard deviation of all the x_'s
double standardDeviationInY(); // computes the standard deviation of all the y_'s
}
重复性导致我有 6 个方法而不是 3 个。成对相似性非常惊人,我可以通过简单地将“x_”替换为“y_”来从 doComputationforX_1 中获得 doComputationforY_1 的实现。
我想过以这种方式重新解决问题:
class PopulationMember
{
public:
vector<vector<int>> data_; // data[0] == x_ and data[1] == y_
}
但这样就变得不太清楚了。
我知道预编译器宏通常是一个糟糕的解决方案,但我没有看到任何其他解决方案。我的潜意识一直在建议模板,但我就是不知道如何使用它们。