In this chapter we shall study 2 new concepts of C++.
1. Initializer List
2. Static Assertions
1. Initializer List
It is used to initialize data members of a class or to create a container of elements.
It can be created using braced list syntax, for example {1, 2, 3}.
It will create a sequence of integers and will be of type std::initiaizer_list<int>.
Example:
int sum(const std::initializer_list<int>& list) {
int total = 0;
for (auto& e : list) {
total += e;
}
return total;
}
auto list = {1, 2, 3};
sum(list); // == 6
sum({1, 2, 3}); // == 6
sum({}); // == 0
2. Static Assertions
Static assertions are evaluated compile time.
It is used to check if the condition is true or false at the compile time.
Syntax:
static_assert( constant_expression, string_literal );
Prior to C++ 11 the only way to produce the compile time error messages is by using “#error” directive.
Example:
constexpr int x = 0;
constexpr int y = 1;
static_assert(x == y, "x != y");