C++中许多具有相同结构的成员函数
Many member functions with the same structure in C++
假设我有一个 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 );
};
所有 setter 定义的结构都是相同的。我很不高兴在这里看到这个复制粘贴。有没有 C++
的风格来摆脱这个?
其实是有办法的。无论如何,它消除了重复,但我仍然认为有这么多 setter 是设计缺陷的标志。
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;
}
};
使用class的代码将写成如下:
A a;
a.SetP<0>(2, 3.0);
SFINAE 技巧确保 i
只能在范围内使用。您也可以 static_assert
像 François Andrieux 在评论中建议的那样。
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 );
假设我有一个 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 );
};
所有 setter 定义的结构都是相同的。我很不高兴在这里看到这个复制粘贴。有没有 C++
的风格来摆脱这个?
其实是有办法的。无论如何,它消除了重复,但我仍然认为有这么多 setter 是设计缺陷的标志。
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;
}
};
使用class的代码将写成如下:
A a;
a.SetP<0>(2, 3.0);
SFINAE 技巧确保 i
只能在范围内使用。您也可以 static_assert
像 François Andrieux 在评论中建议的那样。
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 );