如何使用C ++中的模板来避免这种重复的代码

时间:2012-03-08 04:48:43

标签: c++ templates duplication

我想消除此问题中的双重代码:

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

但这种方式变得不那么明确了。

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

2 个答案:

答案 0 :(得分:2)

如果您想将x_y_分开放在同一个class PopulationMember中,那么最好选择按值传递解决方案而不是template解决方案:

将通用方法定义为:

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

将其命名为:

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

请注意,如果您的doComputationfor足够大,那么强加template方法会导致代码重复。
使用指向成员方法的指针,您将避免代码重复,并且运行时间有点损失。

答案 1 :(得分:1)

如果您指定的API正是您希望该类用户看到的内容,那么只需在名为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; }

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