【发布时间】:2015-09-28 22:19:15
【问题描述】:
所以,我是使用模板的新手,我有一个问题。由于模板是在编译时处理的,而且数组大小必须在编译时设置,我可以使用模板来设置数组大小吗?
template<const size_t N> struct Stats {
// Member functions (omitted).
// The stats themselves.
int stats[N];
};
class DudeWithStats {
public:
void setStats(int sts[], size_t sz, bool derived = false);
// Other member functions (omitted).
private:
Stats<8> base;
Stats<5> derived;
// Other member variables (omitted).
};
void DudeWithStats::setStats(int sts[], size_t sz, bool drvd /* = false */) {
for (int i = 0; i < sz; i++) {
if (drvd) {
derived.stats[i] = sts[i];
} else {
base.stats[i] = sts[i];
}
}
}
int main() {
int arrBase[8] = { 10, 20, 10, 10, 30, 10, 15, 6 };
int arrDerived[5] = { 34, 29, 42, 100, 3 };
DudeWithStats example;
example.setStats(arrBase, 8);
example.setStats(arrDerived, 5, true);
}
我可以看到用new 或std::vector 制作一个动态数组,但我很好奇这是否可行。
(是的,我知道const 在模板声明中毫无意义,至少对编译器而言。它主要用于文档。)
提前致谢。
(编辑:注意到我在 setStats()' 定义中有默认参数。修复了这个问题。修复了函数本身,我相信(以前从未直接复制数组)。)
(编辑:将其切换为 size_t。仍在努力让 setStats() 工作,我可能会坚持手动传递统计信息,而不是作为数组传递。)
(编辑:刚刚使用了一种解决方法来让 setStats() 工作。看起来有点尴尬,但对于测试代码来说已经足够了。)
感谢大家的回答和帮助。我会使用类似的东西来满足我的需要,并随着我的编码能力的提高而改进它。
【问题讨论】:
-
你尝试的时候发生了什么?
-
你的模板参数应该是
size_t类型的 -
如果你没有做错任何事情,它会起作用。只是通常,这些数组都是不同类型的,这很快就会变得很烦人。但如果这不是问题,这种方法是可以的。
-
这种事情不管模板都行不通:
derived.stats = sts;Arrays are not assignable。 -
如果你使用
std::array<int, N> stats;,那么你可以使用赋值运算符来复制数组。
标签: c++