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 instantiated3 static_assert(is_default_constructible_v<T>, "T must be default constructible"); // Limits the size of T to 64 bytes4 static_assert(sizeof(T) <= 64, "T is too large for this container");5 T data;6public: // = default uses the compiler-generated constructor7 SafeContainer() = default; // Stores a copy of the value8 SafeContainer(const T& v) : data(v) {}9 T get() const { return data; }10};11 // A failing condition would stop compilation with this message12static_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 template15SafeContainer<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. 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