我有一个派生类接口,我的基类需要为其定义以下三个受保护的成员数组:
template<size_t n> class Base{
public:
static constexpr size_t n_ = n;
};
class BaseCat: protected Base<4>{
private:
// define arrays conveniently here, using brace notation
double A0[] = {0,1,2,3,4,5,6,7,8,9}; // this is the desired part
double A1[] = {13,-2};
// ...
protected:
// the following three lines are the boilerplate
double* A[] = {A0,A1,A2,A3}; // this is the undesired part
double* x[] = {x0,x1,x2,x3};
double* b[] = {b0,b1,b2,b3};
};
// the implementation of "Derived" requires A[],x[],b[] of length n to exist.
using DerivedCat = Derived<CatBase,CatBase::n_>;
这可以是为每个类 BaseDog:Base<3>、BaseCat:Base<4>、BaseMouse:Base<24> 编写的代码,每次我在 A、x、b 中为相应模型硬编码一些多面体。派生类 ProcessedBase
据我了解,不能使用宏,因为
n
,它的值不一定总是4。
模板函数也不能使用,因为 A0,A1,... 是手写的变量名,因此它们必须依次手写在模板赋值函数中,并且必须传递给它,即与将它们写入大括号括起来的列表一样多的样板。
最后,人们可以尝试在 Base 的基数中强制将名称 A0 映射到 A[i],但是通过上部大括号括起来的列表来方便地定义 A0 是不可能的。
我可以两全其美,即保留所需的部分,同时避免代码中注释的不需要的部分吗?
这对你有用吗?
template <size_t n> class Base
{
public:
static constexpr size_t n_ = n;
};
class BaseCat: protected Base <4>
{
protected:
double A [n_] [10] =
{
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
{ 13, -2 },
{ 14, -3 },
{ 15, -4 }
};
// x, b, ...
};
这几乎就是@463035818_is_not_an_ai所说的。
请注意,这为
A
保留的存储空间比实际需要的要多,但这对您来说可能不是问题。现在绝对是考虑制作 A
const
(或 static constexpr
)的时候了。