c++ - C++:我可以有非静态成员变量模板吗?
问题描述
我正在尝试编写一些代码,要求我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;
}
}
};
我希望代码扩展,就好像它只有 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.
};
据我了解,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>();
推荐阅读
- php - 数组作为 Laravel 表单中的输入(提交功能不起作用)
- javascript - 无法在角度中找到 CSS
- powerquery - 从 power 查询中的表中获取前 n 个结果,其中 n 是基于 if 函数的动态
- sql-server - 如何找到两个连续日期之间的比率值
- javascript - 如何确保鼠标滚轮/滚轮事件在可滚动 div 内每次滚动时仅触发一次
- networking - ZeroMQ:如何实现客户端通知?
- javascript - 将值分配给动态更改其 id 的输入字段
- qt - 从节点属性读取数据类型
- excel - 使用 CountIfs 检查单元格是否有日期或为空
- python - 将文件路径传输到另一个类并将项目添加到列表