简体   繁体   中英

Many member functions with the same structure in C++

Suppose I have a class:

class A {

protected:

  vector<double> p1;
  vector<double> p2;
  ...
  vector<double> pn;

public:

//Constructors and destructor
  void SetP1( int, double );
  void SetP2( int, double );
  ...
  void SetPn( int, double );

};

Where the structure of all setter's definitions is the same. I am not glad to see this copy-paste here. Is there a C++ 's style to get rid of this?

There is, in fact, a way. It removes the repetition, anyway, but I still think having so many setters is a sign of a design flaw.

class A {
  static const int n = /*user-defined*/;
  std::array<std::vector<double>, n> p;

  template<int i, std::enable_if_t<i < n, int> = 0>
  void SetP(int j, double d) {
    // example code, no error handling;
    p[i][j] = d;
  }
};

Code that uses the class would be written as follows:

A a;
a.SetP<0>(2, 3.0);

And the SFINAE trick ensures i can only be used in range. You can also static_assert like François Andrieux suggested in a comment.

class A {
public:
  enum {count = 55};
protected:
  std::array<std::vector<double>, count> p;
public:

//Constructors and destructor
  template<std::size_t N>
  void SetP( std::size_t x, double d ) {
    static_assert( N<count, "out of bounds" );
    // I assume we want auto-resize:
    if (x >= p[N].size()) p[N].resize(x+1);
    p[N][x] = d;
  }
};

Use:

A a;
a.SetP<22>( 7, 3.14 );

live example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM