how to avoid this duplicate code using templates in C++ -


i eliminate duplicity of code in problem:

class populationmember { public:     vector<int> x_;     vector<int> y_; }  class population {     vector<populationmember*> members_;      void docomputationforx_1();  // uses attribute x_ of members_     void docomputationforx_2();       void docomputationforx_3();      void docomputationfory_1();  // same docomputationforx_1,      void docomputationfory_2();  // uses attribute y_ of members_     void docomputationfory_3();     edit: // there functions use members_ simultaniously      double standarddeviationinx(); // computes standard deviation of x_'s     double standarddeviationiny(); // computes standard deviation of y_'s } 

the duplicity causing me have 6 methods instead of 3. pairwise similarity striking, can implementation of docomputationfory_1 out of docomputationforx_1 replacing "x_" "y_".

i thought remaking problem in way:

class populationmember { public:     vector<vector<int>> data_; // data[0] == x_ , data[1] == y_  }  

but becomes less clear way.

i know precompiler macro bad solution in general, not see other. subconciousness keeps suggesting templates, not see how can use them.

if want keep x_ , y_ separately in same class populationmember it's better choose pass value solution rather template solution:

define generic method as:

void docomputationfor (vector<int> (populationmember::*member_));                 // pointer data  ^^^^^^^^^^^^^^^^^^^^^^^^^^ 

call as:

docomputationfor(&populationmember::x_); docomputationfor(&populationmember::y_); 

remember if docomputationfor large enough then, imposing template method make code duplication.
pointer member method, avoid code duplication little runtime penalty.


Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -