So, I'm new to using templates, and I have a question. Since templates are handled at compile time, and array size has to be set at compile time, can I use a template to set array size?
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);
}
I can see making a dynamic array with new
or std::vector
working out, but I'm curious as to whether this would work.
(Yes, I know const
is meaningless in template declaration, at least to the compiler. It's mainly there for documentation.)
Thanks in advance.
(Edit: Noticed I had the default argument in setStats()' definition. Fixed that. Fixed the function itself, too, I believe (never had to directly copy an array before).)
(Edit: Switched it to a size_t. Still working on getting setStats() to work, I'll probably just stick with passing the stats manually instead of as an array.)
(Edit: Just used a workaround to get setStats() working. It looks a bit awkward, but it's good enough for test code.)
Thanks for answering and helping, everyone. I'll use something similar to that for what I need, and improve it as I get better at coding.