0

recently I knew a new template usage like below

template <unsigned int N>

I saw the answer here
What does template <unsigned int N> mean? It showed several examples includes:

template<unsigned int S>
struct Vector {
    unsigned char bytes[S];
};

However, I cannot figure out the point of this usage. Why don't we just use class initialization to do this work. What's the point of using a template here?

Community
  • 1
  • 1
Peter Ye
  • 59
  • 4
  • 4
    Assume you tried to pass the size to a constructor. The compiler must parse the class definition before any constructor is called. What's the object size? – StoryTeller - Unslander Monica May 10 '17 at 08:29
  • The "standard type" would be `std::array` which is pretty much identical to this `vector`. Calling this `Vector` might suggest a similarity to `std::vector`. And that's precisely the relevant difference: compile-time versus run-time sizing. – MSalters May 10 '17 at 15:00

1 Answers1

1

The size of a class must be known at compile-time. So you can't provide the size at class initialization time. This includes the size of any fixed-sized arrays included in the class.

To confuse matters there are some compiler extensions that allow you to use the syntax of fixed-size arrays with dynamically allocated size but this is not standard C++.

Even classes like std::vector have a fixed size but they use dynamic memory allocation for their contents so the size of the contents can be provided at class initialization time. Such containers contain a pointer to the dynamically allocated memory instead of a fixed-size array.

Chris Drew
  • 14,926
  • 3
  • 34
  • 54
  • *"To confuse matters there are some compiler extensions that allow you to use the syntax of fixed-size arrays with dynamically allocated size"* - Not as class members however, if memory serves. – StoryTeller - Unslander Monica May 10 '17 at 08:51
  • @StoryTeller: IIRC, one common extension is to support VLA's as the _last_ member of a class. – MSalters May 10 '17 at 15:03
  • @MSalters - You mean flexible array members? Those must be last and aren't accounted for in the types size as returned by sizeof. They are standard C99, but I am not aware of a compiler that offers such an extension for C++. – StoryTeller - Unslander Monica May 10 '17 at 18:10