我正在尝试编写一些代码,要求我std::array在容器类中有很多s.这些阵列都有不同的大小(如果重要的话,所有阵列都是2-16连续),并且每种大小都有一个.我想将它们放在容器类中,并能够使用模板访问它们.
用代码解释可能更容易.我想要这样的东西:
class ContainerClass {
public:
// I want to declare some number of arrays right here, all of different
// sizes, ranging from 2-16. I'd like to be able to access them as
// arr<2> through arr<16>.
// This code gives a compiler error, understandably.
// But this is what I'd think it'd look like.
template <size_t N> // I also need to find a way to restrict N to 2 through 16.
std::array<int, N> arr;
// An example method of how I want to be able to use this.
template <size_t N>
void printOutArr() {
for (int i = 0; i < N; i++) {
std::cout << arr<N>[i] << std::endl;
}
}
};
Run Code Online (Sandbox Code Playgroud)
我希望代码扩展,好像它只有15个数组,从2到16.像这样,但有模板:
class ContainerClass {
public:
std::array<int, 2> arr2;
std::array<int, 3> arr3;
std::array<int, 4> arr4;
std::array<int, 5> arr5;
// ... and so on.
};
Run Code Online (Sandbox Code Playgroud)
据我所知,C++支持变量模板,但它似乎只适用于类中的静态成员.是否存在可以表现相似的替代方案(最好是尽可能少的开销)?
如果您需要更多信息,请询问.
提前致谢.
我可以拥有非静态成员变量模板吗?
没有.
但是,您可以使用模板生成您描述的成员列表.以下是使用递归继承的示例:
template<class T, std::size_t base, std::size_t size>
class Stair;
template<class T, std::size_t base>
class Stair<T, base, base> {};
template<class T, std::size_t base, std::size_t size>
class Stair : Stair<T, base, size - 1> {
protected:
std::array<T, size> arr;
public:
template<std::size_t s>
std::array<T, s>& array() {
return Stair<T, base, s>::arr;
}
};
int main()
{
Stair<int, 2, 10> s;
auto& arr = s.array<9>();
Run Code Online (Sandbox Code Playgroud)