c++templatesc++17class-templatecompile-time-type-checking

Enforce compile time maximum value to a integral constant expression


I have a template class like so:

template<typename T, unsigned int size>
class Array 
{
public:
  static const unsigned int SIZE = size;
  // ...
private:
  T data[SIZE];
};

Is there a way to add compile-time checks such that the size of an Array<T,XXXX> never exceeds a certain value?

Like if that value was 512, this shouldn't compile:

Array<int, 1000> arr;


This idea of C++ifiying my code is new to me, so I'm open to any guides or further learning online to help with this since I didn't even know what to google for this. Everything I tried seemed way off.


Solution

  • Is there a way to add compile-time checks such that the size of an Array<T,XXXX> never exceeds a certain value?

    You can use requires in C++20 for this

    template<typename T, unsigned int size> requires (size < 512)
    class Array 
    {
           // .....
    };
    

    Alternatively, you can static_assert the condition inside the class definition with a meaningful message to the user.

    template<typename T, unsigned int size>
    class Array 
    {
         static_assert(size < 512, "Array size exceeded");
         // ....
    };