Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");
     // ....
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading