c++ - C++中许多具有相同结构的成员函数

标签 c++ class member

假设我有一个类:

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 );

};

所有 setter 定义的结构都是相同的。我很不高兴在这里看到这个复制粘贴。有没有 C++ 的风格来摆脱这个?

最佳答案

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

使用:

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

live example .

关于c++ - C++中许多具有相同结构的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43744532/

相关文章:

java - 在 Java 中创建类数组(而不是对象)?

c++ - 对于结构中的数组,我可以期待哪些对齐保证?

C++ 使用来自 const 函数的映射调用指向成员的指针

c++ - 无法使用来自 QString 的 const char * 进行 fopen

c++ - 将派生类构造函数参数传递给 protected 成员

c++ - 试图向下转换 std::vector 中对象的指针

c++ - this 指针和成员函数地址

c++ - 如何修改 C++ 中的 const 引用

python - 这个变量 `instantiated` 的范围是什么

python - python字符串类在源代码中的位置