Static Assert in C++

Level 5565 keystrokes

static_assert checks a condition at compile time and stops compilation with the given message if it is false. Here it checks requirements on the template parameter T and assumptions about int; both instantiations pass, so the program runs normally.

C++ code

1template<typename T>
2class SafeContainer {
// Checked for each T when the template is instantiated
3 static_assert(is_default_constructible_v<T>, "T must be default constructible");
// Limits the size of T to 64 bytes
4 static_assert(sizeof(T) <= 64, "T is too large for this container");
5 T data;
6public:
// = default uses the compiler-generated constructor
7 SafeContainer() = default;
// Stores a copy of the value
8 SafeContainer(const T& v) : data(v) {}
9 T get() const { return data; }
10};
11
// A failing condition would stop compilation with this message
12static_assert(sizeof(int) == 4, "int must be 4 bytes");
13static_assert(is_integral_v<int>, "int must be integral");
14
// int passes both checks of the template
15SafeContainer<int> ci(42);
// string also passes (its size is usually 24 or 32 bytes)
16SafeContainer<string> cs("hello");
17
// Prints "Int: 42"
18cout << "Int: " << ci.get() << endl;
// Prints "String: hello"
19cout << "String: " << cs.get() << endl;

Output

Int: 42
String: hello
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 18
  • "× 14
  • (× 14
  • )× 14
  • ;× 12
  • _× 9
  • >× 5
  • ,× 4
  • :× 4
  • =× 4

More C++ examples at level 5

← C++ typing practice