1

我想消除这个问题中的代码重复:

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_ 
} 

但这样就变得不太清楚了。

我知道预编译器宏通常是一个糟糕的解决方案,但我没有看到任何其他解决方案。我的潜意识一直在建议模板,但我就是不知道如何使用它们。

4

2 回答 2

2

如果您想保持x_y_分开相同class PopulationMember,那么最好选择传递值解决方案而不是template解决方案:

将泛型方法定义为:

void doComputationfor (vector<int> (PopulationMember::*member_));
                // pointer to data  ^^^^^^^^^^^^^^^^^^^^^^^^^^

称它为:

doComputationfor(&PopulationMember::x_);
doComputationfor(&PopulationMember::y_);

请记住,如果您doComputationfor的规模足够大,那么强加template方法会导致代码重复。
使用指向成员方法的指针,您将避免代码重复,但会带来一点运行时损失。

于 2012-03-08T04:58:04.853 回答
1

如果您指定的 API 正是您希望该类的用户看到的,那么只需在 Population 中调用私有方法doComputation_1( const vector<int> &v ) { do stuff on v; }

然后将公共实现设为 1 行:

public:
    void DoComputationX_1() { doComputation_1( x_ ); }
    void DoComputationY_1() { doComputation_1( y_ ); }
private:
    // drop the 'const' if you will need to modify the vector
    void doComputation_1( const vector<int> &v ) { do stuff on v; }

我觉得这不是正确的解决方案,但我无法拼凑出你的班级真正想要做的事情,以便提供更有意义的东西。

于 2012-03-08T04:55:01.380 回答