Chapter 02: Language Usability Enhancements

When we declare, define a variable or constant, and control the flow of code, object-oriented functions, template programming, etc., before the runtime, it may happen when writing code or compiler compiling code. To this end, we usually talk about language usability, which refers to the language behavior that occurred before the runtime.

2.1 Constants

nullptr

The purpose of nullptr appears to replace NULL. In a sense, traditional C++ treats NULL and 0 as the same thing, depending on how the compiler defines NULL, and some compilers define NULL as ((void*)0) Some will define it directly as 0.

C++ does not allow to implicitly convert void * to other types. But if the compiler tries to define NULL as ((void*)0), then in the following code:

  1. char *ch = NULL;

C++ without the void * implicit conversion has to define NULL as 0. This still creates a new problem. Defining NULL to 0 will cause the overloading feature in C++ to be confusing. Consider the following two foo functions:

  1. void foo(char*);
  2. void foo(int);

Then the foo(NULL); statement will call foo(int), which will cause the code to be counterintuitive.

To solve this problem, C++11 introduced the nullptr keyword, which is specifically used to distinguish null pointers, 0. The type of nullptr is nullptr_t, which can be implicitly converted to any pointer or member pointer type, and can be compared equally or unequally with them.

You can try to compile the following code using clang++:

  1. #include <iostream>
  2. #include <type_traits>
  3. void foo(char *);
  4. void foo(int);
  5. int main() {
  6. if (std::is_same<decltype(NULL), decltype(0)>::value)
  7. std::cout << "NULL == 0" << std::endl;
  8. if (std::is_same<decltype(NULL), decltype((void*)0)>::value)
  9. std::cout << "NULL == (void *)0" << std::endl;
  10. if (std::is_same<decltype(NULL), std::nullptr_t>::value)
  11. std::cout << "NULL == nullptr" << std::endl;
  12. foo(0); // will call foo(int)
  13. // foo(NULL); // doesn't compile
  14. foo(nullptr); // will call foo(char*)
  15. return 0;
  16. }
  17. void foo(char *) {
  18. std::cout << "foo(char*) is called" << std::endl;
  19. }
  20. void foo(int i) {
  21. std::cout << "foo(int) is called" << std::endl;
  22. }

The outputs are:

  1. foo(int) is called
  2. foo(char*) is called

From the output we can see that NULL is different from 0 and nullptr. So, develop the habit of using nullptr directly.

In addition, in the above code, we used decltype and std::is_same which are modern C++ syntax. In simple terms, decltype is used for type derivation, and std::is_same is used. To compare the equality of the two types, we will discuss them in detail later in the decltype section.

constexpr

C++ itself already has the concept of constant expressions, such as 1+2, 3*4. Such expressions always produce the same result without any side effects. If the compiler can directly optimize and embed these expressions into the program at compile time, it will increase the performance of the program. A very obvious example is in the definition phase of an array:

  1. #include <iostream>
  2. #define LEN 10
  3. int len_foo() {
  4. int i = 2;
  5. return i;
  6. }
  7. constexpr int len_foo_constexpr() {
  8. return 5;
  9. }
  10. constexpr int fibonacci(const int n) {
  11. return n == 1 || n == 2 ? 1 : fibonacci(n-1) + fibonacci(n-2);
  12. }
  13. int main() {
  14. char arr_1[10]; // legal
  15. char arr_2[LEN]; // legal
  16. int len = 10;
  17. // char arr_3[len]; // illegal
  18. const int len_2 = len + 1;
  19. constexpr int len_2_constexpr = 1 + 2 + 3;
  20. // char arr_4[len_2]; // illegal, but ok for most of the compilers
  21. char arr_4[len_2_constexpr]; // legal
  22. // char arr_5[len_foo()+5]; // illegal
  23. char arr_6[len_foo_constexpr() + 1]; // legal
  24. // 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
  25. std::cout << fibonacci(10) << std::endl;
  26. return 0;
  27. }

In the above example, char arr_4[len_2] may be confusing because len_2 has been defined as a constant. Why is char arr_4[len_2] still illegal? This is because the length of the array in the C++ standard must be a constant expression, and for len_2, this is a const constant, not a constant expression, so even if this behavior is in most compilers Both support, but) it is an illegal behavior, we need to use the constexpr feature introduced in C++11, which will be introduced next, to solve this problem; for arr_5, before C++98 The compiler cannot know that len_foo() actually returns a constant at runtime, which causes illegal production.

Note that most compilers now have their own compiler optimizations. Many illegal behaviors become legal under the compiler’s optimization. If you need to reproduce the error, you need to use the old version of the compiler.

C++11 provides constexpr to let the user explicitly declare that the function or object constructor will become a constant expression at compile time. This keyword explicitly tells the compiler that it should verify that len_foo should be a compile time. Constant expression.

In addition, the function of constexpr can use recursion:

  1. constexpr int fibonacci(const int n) {
  2. return n == 1 || n == 2 ? 1 : fibonacci(n-1) + fibonacci(n-2);
  3. }

Starting with C++14, the constexpr function can use simple statements such as local variables, loops, and branches internally. For example, the following code cannot be compiled under the C++11 standard:

  1. constexpr int fibonacci(const int n) {
  2. if(n == 1) return 1;
  3. if(n == 2) return 1;
  4. return fibonacci(n-1) + fibonacci(n-2);
  5. }

To do this, we can write a simplified version like this to make the function available from C++11:

  1. constexpr int fibonacci(const int n) {
  2. return n == 1 || n == 2 ? 1 : fibonacci(n-1) + fibonacci(n-2);
  3. }

2.2 Variables and initialization

if-switch

In traditional C++, the declaration of a variable can declare a temporary variable int even though it can be located anywhere, even within a for statement, but there is always no way to declare a temporary variable in the if and switch statements. E.g:

  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. int main() {
  5. std::vector<int> vec = {1, 2, 3, 4};
  6. // after c++17, can be simplefied by using `auto`
  7. const std::vector<int>::iterator itr = std::find(vec.begin(), vec.end(), 2);
  8. if (itr != vec.end()) {
  9. *itr = 3;
  10. }
  11. if (const std::vector<int>::iterator itr = std::find(vec.begin(), vec.end(), 3);
  12. itr != vec.end()) {
  13. *itr = 4;
  14. }
  15. // should output: 1, 4, 3, 4. can be simplefied using `auto`
  16. for (std::vector<int>::iterator element = vec.begin(); element != vec.end(); ++element)
  17. std::cout << *element << std::endl;
  18. }

In the above code, we can see that the itr variable is defined in the scope of the entire main(), which causes us to rename the other when we need to traverse the entire std::vectors again. A variable. C++17 eliminates this limitation so that we can do this in if(or switch):

  1. if (const std::vector<int>::iterator itr = std::find(vec.begin(), vec.end(), 3);
  2. itr != vec.end()) {
  3. *itr = 4;
  4. }

Is it similar to the Go?

Initializer list

Initialization is a very important language feature, the most common one is when the object is initialized. In traditional C++, different objects have different initialization methods, such as ordinary arrays, PODs (Plain Old Data, ie classes without constructs, destructors, and virtual functions) Or struct type can be initialized with {}, which is what we call the initialization list. For the initialization of the class object, you need to use the copy construct, or you need to use (). These different methods are specific to each other and cannot be generic. E.g:

  1. #include <iostream>
  2. #include <vector>
  3. class Foo {
  4. public:
  5. int value_a;
  6. int value_b;
  7. Foo(int a, int b) : value_a(a), value_b(b) {}
  8. };
  9. int main() {
  10. // before C++11
  11. int arr[3] = {1, 2, 3};
  12. Foo foo(1, 2);
  13. std::vector<int> vec = {1, 2, 3, 4, 5};
  14. std::cout << "arr[0]: " << arr[0] << std::endl;
  15. std::cout << "foo:" << foo.value_a << ", " << foo.value_b << std::endl;
  16. for (std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {
  17. std::cout << *it << std::endl;
  18. }
  19. return 0;
  20. }

To solve this problem, C++11 first binds the concept of the initialization list to the type and calls it std::initializer_list, allowing the constructor or other function to use the initialization list like a parameter, which is The initialization of class objects provides a unified bridge between normal arrays and POD initialization methods, such as:

  1. #include <initializer_list>
  2. #include <vector>
  3. class MagicFoo {
  4. public:
  5. std::vector<int> vec;
  6. MagicFoo(std::initializer_list<int> list) {
  7. for (std::initializer_list<int>::iterator it = list.begin();
  8. it != list.end(); ++it)
  9. vec.push_back(*it);
  10. }
  11. };
  12. int main() {
  13. // after C++11
  14. MagicFoo magicFoo = {1, 2, 3, 4, 5};
  15. std::cout << "magicFoo: ";
  16. for (std::vector<int>::iterator it = magicFoo.vec.begin(); it != magicFoo.vec.end(); ++it) std::cout << *it << std::endl;
  17. }

This constructor is called the initialize list constructor, and the type with this constructor will be specially taken care of during initialization.

In addition to the object construction, the initialization list can also be used as a formal parameter of a normal function, for example:

  1. public:
  2. void foo(std::initializer_list<int> list) {
  3. for (std::initializer_list<int>::iterator it = list.begin(); it != list.end(); ++it) vec.push_back(*it);
  4. }
  5. magicFoo.foo({6,7,8,9});

Second, C++11 also provides a uniform syntax for initializing arbitrary objects, such as:

  1. Foo foo2 {3, 4};

Structured binding

Structured bindings provide functionality similar to the multiple return values provided in other languages. In the chapter on containers, we will learn that C++11 has added a std::tuple container for constructing a tuple that encloses multiple return values. But the flaw is that C++11/14 does not provide a simple way to get and define the elements in the tuple directly from the tuple, although we can unpack the tuple using std::tie But we still have to be very clear about how many objects this tuple contains, what type of each object is, very troublesome.

C++17 completes this setting, and the structured bindings let us write code like this:

  1. #include <iostream>
  2. #include <tuple>
  3. std::tuple<int, double, std::string> f() {
  4. return std::make_tuple(1, 2.3, "456");
  5. }
  6. int main() {
  7. auto [x, y, z] = f();
  8. std::cout << x << ", " << y << ", " << z << std::endl;
  9. return 0;
  10. }

The auto type derivation is described in the auto type inference section.

2.3 Type inference

In traditional C and C++, the types of parameters must be clearly defined, which does not help us to quickly encode, especially when we are faced with a large number of complex template types, we must clearly indicate the type of variables in order to proceed. Subsequent coding, which not only slows down our development efficiency, but also makes the code stinking and long.

C++11 introduces the two keywords auto and decltype to implement type derivation, letting the compiler worry about the type of the variable. This makes C++ the same as other modern programming languages, in a way that provides the habit of not having to worry about variable types.

auto

auto has been in C++ for a long time, but it always exists as an indicator of a storage type, coexisting with register. In traditional C++, if a variable is not declared as a register variable, it is automatically treated as an auto variable. And with register being deprecated (used as a reserved keyword in C++17 and later used, it doesn’t currently make sense), the semantic change to auto is very natural.

One of the most common and notable examples of type derivation using auto is the iterator. You should see the lengthy iterative writing in traditional C++ in the previous section:

  1. // before C++11
  2. // cbegin() returns vector<int>::const_iterator
  3. // and therefore itr is type vector<int>::const_iterator
  4. for(vector<int>::const_iterator it = vec.cbegin(); itr != vec.cend(); ++it)

When we have auto:

  1. #include <initializer_list>
  2. #include <vector>
  3. #include <iostream>
  4. class MagicFoo {
  5. public:
  6. std::vector<int> vec;
  7. MagicFoo(std::initializer_list<int> list) {
  8. for (auto it = list.begin(); it != list.end(); ++it) {
  9. vec.push_back(*it);
  10. }
  11. }
  12. };
  13. int main() {
  14. MagicFoo magicFoo = {1, 2, 3, 4, 5};
  15. std::cout << "magicFoo: ";
  16. for (auto it = magicFoo.vec.begin(); it != magicFoo.vec.end(); ++it) {
  17. std::cout << *it << ", ";
  18. }
  19. std::cout << std::endl;
  20. return 0;
  21. }

Some other common usages:

  1. auto i = 5; // i as int
  2. auto arr = new auto(10); // arr as int *

Note: auto cannot be used for function arguments, so the following is not possible to compile (considering overloading, we should use templates):

  1. int add(auto x, auto y);
  2. 2.6.auto.cpp:16:9: error: 'auto' not allowed in function prototype
  3. int add(auto x, auto y) {
  4. ^~~~

In addition, auto cannot be used to derive array types:

  1. auto auto_arr2[10] = arr; // illegal, can't infer array type
  2. 2.6.auto.cpp:30:19: error: 'auto_arr2' declared as array of 'auto'
  3. auto auto_arr2[10] = arr;

decltype

The decltype keyword is used to solve the defect that the auto keyword can only type the variable. Its usage is very similar to sizeof:

  1. decltype(expression)

Sometimes we may need to calculate the type of an expression, for example:

  1. auto x = 1;
  2. auto y = 2;
  3. decltype(x+y) z;

You have seen in the previous example that decltype is used to infer the usage of the type. The following example is to determine if the above variables x, y, z are of the same type:

  1. if (std::is_same<decltype(x), int>::value)
  2. std::cout << "type x == int" << std::endl;
  3. if (std::is_same<decltype(x), float>::value)
  4. std::cout << "type x == float" << std::endl;
  5. if (std::is_same<decltype(x), decltype(z)>::value)
  6. std::cout << "type z == type x" << std::endl;

Among them, std::is_same<T, U> is used to determine whether the two types T and U are equal. The output is:

  1. type x == int
  2. type z == type x

tail type inference

You may think that when we introduce auto, we have already mentioned that auto cannot be used for function arguments for type derivation. Can auto be used to derive the return type of a function? Still consider an example of an add function, which we have to write in traditional C++:

  1. template<typename R, typename T, typename U>
  2. R add(T x, U y) {
  3. return x+y
  4. }

Note: There is no difference between typename and class in the template parameter list. Before the keyword typename appears, class is used to define the template parameters. However, when defining a variable with nested dependency type in the template, you need to use typename to eliminate ambiguity.

Such code is actually very ugly, because the programmer must explicitly indicate the return type when using this template function. But in fact we don’t know what kind of operation the add() function will do, and what kind of return type to get.

This problem was solved in C++11. Although you may immediately react to using decltype to derive the type of x+y, write something like this:

  1. decltype(x+y) add(T x, U y)

But in fact, this way of writing can not be compiled. This is because x and y have not been defined when the compiler reads decltype(x+y). To solve this problem, C++11 also introduces a trailing return type, which uses the auto keyword to post the return type:

  1. template<typename T, typename U>
  2. auto add2(T x, U y) -> decltype(x+y){
  3. return x + y;
  4. }

The good news is that from C++14 it is possible to directly derive the return value of a normal function, so the following way becomes legal:

  1. template<typename T, typename U>
  2. auto add3(T x, U y){
  3. return x + y;
  4. }

You can check if the type derivation is correct:

  1. // after c++11
  2. auto w = add2<int, double>(1, 2.0);
  3. if (std::is_same<decltype(w), double>::value) {
  4. std::cout << "w is double: ";
  5. }
  6. std::cout << w << std::endl;
  7. // after c++14
  8. auto q = add3<double, int>(1.0, 2);
  9. std::cout << "q: " << q << std::endl;

decltype(auto)

decltype(auto) is a slightly more complicated use of C++14.

To understand it you need to know the concept of parameter forwarding in C++, which we will cover in detail in the Language Runtime Hardening chapter, and you can come back to the contents of this section later.

In simple terms, decltype(auto) is mainly used to derive the return type of a forwarding function or package, which does not require us to explicitly specify the parameter expression of decltype. Consider the following example, when we need to wrap the following two functions:

  1. std::string lookup1();
  2. std::string& lookup2();

In C++11:

  1. std::string look_up_a_string_1() {
  2. return lookup1();
  3. }
  4. std::string& look_up_a_string_2() {
  5. return lookup2();
  6. }

With decltype(auto), we can let the compiler do this annoying parameter forwarding:

  1. decltype(auto) look_up_a_string_1() {
  2. return lookup1();
  3. }
  4. decltype(auto) look_up_a_string_2() {
  5. return lookup2();
  6. }

2.4 Control flow

if constexpr

As we saw at the beginning of this chapter, we know that C++11 introduces the constexpr keyword, which compiles expressions or functions into constant results. A natural idea is that if we introduce this feature into the conditional judgment, let the code complete the branch judgment at compile time, can it make the program more efficient? C++17 introduces the constexpr keyword into the if statement, allowing you to declare the condition of a constant expression in your code. Consider the following code:

  1. #include <iostream>
  2. template<typename T>
  3. auto print_type_info(const T& t) {
  4. if constexpr (std::is_integral<T>::value) {
  5. return t + 1;
  6. } else {
  7. return t + 0.001;
  8. }
  9. }
  10. int main() {
  11. std::cout << print_type_info(5) << std::endl;
  12. std::cout << print_type_info(3.14) << std::endl;
  13. }

At compile time, the actual code will behave as follows:

  1. int print_type_info(const int& t) {
  2. return t + 1;
  3. }
  4. double print_type_info(const double& t) {
  5. return t + 0.001;
  6. }
  7. int main() {
  8. std::cout << print_type_info(5) << std::endl;
  9. std::cout << print_type_info(3.14) << std::endl;
  10. }

Range-based for loop

Finally, C++11 introduces a range-based iterative method, and we have the ability to write loops that are as concise as Python, and we can further simplify the previous example:

  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. int main() {
  5. std::vector<int> vec = {1, 2, 3, 4};
  6. if (auto itr = std::find(vec.begin(), vec.end(), 3); itr != vec.end()) *itr = 4;
  7. for (auto element : vec)
  8. std::cout << element << std::endl; // read only
  9. for (auto &element : vec) {
  10. element += 1; // writeable
  11. }
  12. for (auto element : vec)
  13. std::cout << element << std::endl; // read only
  14. }

2.5 Templates

C++ templates have always been a special art of the language, and templates can even be used independently as a new language. The philosophy of the template is to throw all the problems that can be processed at compile time into the compile time, and only deal with those core dynamic services at runtime, so as to greatly optimize the performance of the runtime. Therefore, templates are also regarded by many as one of the black magic of C++.

Extern templates

In traditional C++, templates are instantiated by the compiler only when they are used. In other words, as long as a fully defined template is encountered in the code compiled in each compilation unit (file), it will be instantiated. This results in an increase in compile time due to repeated instantiations. Also, we have no way to tell the compiler not to trigger the instantiation of the template.

To this end, C++11 introduces an external template that extends the syntax of the original mandatory compiler to instantiate a template at a specific location, allowing us to explicitly tell the compiler when to instantiate the template:

  1. template class std::vector<bool>; // force instantiation
  2. extern template class std::vector<double>; // should not instantiation in current file

The “>”

In the traditional C++ compiler, >> is always treated as a right shift operator. But actually we can easily write the code for the nested template:

  1. std::vector<std::vector<int>> matrix;

This is not compiled under the traditional C++ compiler, and C++11 starts with continuous right angle brackets that become legal and can be compiled successfully. Even the following writing can be compiled by:

  1. template<bool T>
  2. class MagicType {
  3. bool magic = T;
  4. };
  5. // in main function:
  6. std::vector<MagicType<(1>2)>> magic; // legal, but not recommended

Type alias templates

Before you understand the type alias template, you need to understand the difference between “template” and “type”. Carefully understand this sentence: Templates are used to generate types. In traditional C++, typedef can define a new name for the type, but there is no way to define a new name for the template. Because the template is not a type. E.g:

  1. template<typename T, typename U>
  2. class MagicType {
  3. public:
  4. T dark;
  5. U magic;
  6. };
  7. // not allowed
  8. template<typename T>
  9. typedef MagicType<std::vector<T>, std::string> FakeDarkMagic;

C++11 uses using to introduce the following form of writing, and at the same time supports the same effect as the traditional typedef:

Usually we use typedef to define the alias syntax: typedef original name new name;, but the definition syntax for aliases such as function pointers is different, which usually causes a certain degree of difficulty for direct reading.

  1. typedef int (*process)(void *);
  2. using NewProcess = int(*)(void *);
  3. template<typename T>
  4. using TrueDarkMagic = MagicType<std::vector<T>, std::string>;
  5. int main() {
  6. TrueDarkMagic<bool> you;
  7. }

Default template parameters

We may have defined an addition function:

  1. template<typename T, typename U>
  2. auto add(T x, U y) -> decltype(x+y) {
  3. return x+y;
  4. }

However, when used, it is found that to use add, you must specify the type of its template parameters each time.

A convenience is provided in C++11 to specify the default parameters of the template:

  1. template<typename T = int, typename U = int>
  2. auto add(T x, U y) -> decltype(x+y) {
  3. return x+y;
  4. }

Variadic templates

The template has always been one of C++’s unique Black Magic. In traditional C++, both a class template and a function template could only accept a fixed set of template parameters as specified; C++11 added a new representation, allowing any number, template parameters of any category, and there is no need to fix the number of parameters when defining.

  1. template<typename... Ts> class Magic;

The template class Magic object can accept unrestricted number of typename as a formal parameter of the template, such as the following definition:

  1. class Magic<int,
  2. std::vector<int>,
  3. std::map<std::string,
  4. std::vector<int>>> darkMagic;

Since it is arbitrary, a template parameter with a number of 0 is also possible: class Magic<> nothing;.

If you do not want to generate 0 template parameters, you can manually define at least one template parameter:

  1. template<typename Require, typename... Args> class Magic;

The variable length parameter template can also be directly adjusted to the template function. The printf function in the traditional C, although it can also reach the call of an indefinite number of formal parameters, is not class safe. In addition to the variable-length parameter functions that define class safety, C++11 can also make printf-like functions naturally handle objects that are not self-contained. In addition to the use of ... in the template parameters to indicate the indefinite length of the template parameters, the function parameters also use the same representation to represent the indefinite length parameters, which provides a convenient means for us to simply write variable length parameter functions, such as:

  1. template<typename... Args> void printf(const std::string &str, Args... args);

Then we define variable length template parameters, how to unpack the parameters?

First, we can use sizeof... to calculate the number of arguments:

  1. #include <iostream>
  2. template<typename... Ts>
  3. void magic(Ts... args) {
  4. std::cout << sizeof...(args) << std::endl;
  5. }

We can pass any number of arguments to the magic function:

  1. magic(); // 0
  2. magic(1); // 1
  3. magic(1, ""); // 2

Second, the parameters are unpacked. So far there is no simple way to process the parameter package, but there are two classic processing methods:

1. Recursive template function

Recursion is a very easy way to think of and the most classic approach. This method continually recursively passes template parameters to the function, thereby achieving the purpose of recursively traversing all template parameters:

  1. #include <iostream>
  2. template<typename T0>
  3. void printf1(T0 value) {
  4. std::cout << value << std::endl;
  5. }
  6. template<typename T, typename... Ts>
  7. void printf1(T value, Ts... args) {
  8. std::cout << value << std::endl;
  9. printf1(args...);
  10. }
  11. int main() {
  12. printf1(1, 2, "123", 1.1);
  13. return 0;
  14. }

2. Variable parameter template expansion

You should feel that this is very cumbersome. Added support for variable parameter template expansion in C++17, so you can write printf in a function:

  1. template<typename T0, typename... T>
  2. void printf2(T0 t0, T... t) {
  3. std::cout << t0 << std::endl;
  4. if constexpr (sizeof...(t) > 0) printf2(t...);
  5. }

In fact, sometimes we use variable parameter templates, but we don’t necessarily need to traverse the parameters one by one. We can use the features of std::bind and perfect forwarding to achieve the binding of functions and parameters, thus achieving success. The purpose of the call.

3. Initialize list expansion

Recursive template functions are a standard practice, but the obvious drawback is that you must define a function that terminates recursion.

Here is a description of the black magic that is expanded using the initialization list:

  1. template<typename T, typename... Ts>
  2. auto printf3(T value, Ts... args) {
  3. std::cout << value << std::endl;
  4. (void) std::initializer_list<T>{([&args] {
  5. std::cout << args << std::endl;
  6. }(), value)...};
  7. }

In this code, the initialization list provided in C++11 and the properties of the Lambda expression (mentioned in the next section) are additionally used.

By initializing the list, (lambda expression, value)... will be expanded. Due to the appearance of the comma expression, the previous lambda expression is executed first, and the output of the parameter is completed. To avoid compiler warnings, we can explicitly convert std::initializer_list to void.

Fold expression

In C++ 17, this feature of the variable length parameter is further brought to the expression, consider the following example:

  1. #include <iostream>
  2. template<typename ... T>
  3. auto sum(T ... t) {
  4. return (t + ...);
  5. }
  6. int main() {
  7. std::cout << sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) << std::endl;
  8. }

Non-type template parameter deduction

What we mainly mentioned above is a form of template parameters: type template parameters.

  1. template <typename T, typename U>
  2. auto add(T t, U u) {
  3. return t+u;
  4. }

The parameters of the template T and U are specific types. But there is also a common form of template parameter that allows different literals to be template parameters, ie non-type template parameters:

  1. template <typename T, int BufSize>
  2. class buffer_t {
  3. public:
  4. T& alloc();
  5. void free(T& item);
  6. private:
  7. T data[BufSize];
  8. }
  9. buffer_t<int, 100> buf; // 100 as template parameter

In this form of template parameters, we can pass 100 as a parameter to the template. After C++11 introduced the feature of type derivation, we will naturally ask, since the template parameters here Passing with a specific literal, can the compiler assist us in type derivation, By using the placeholder auto, there is no longer a need to explicitly specify the type? Fortunately, C++17 introduces this feature, and we can indeed use the auto keyword to let the compiler assist in the completion of specific types of derivation. E.g:

  1. template <auto value> void foo() {
  2. std::cout << value << std::endl;
  3. return;
  4. }
  5. int main() {
  6. foo<10>(); // value as int
  7. }

2.6 Object-oriented

Delegate constructor

C++11 introduces the concept of a delegate construct, which allows a constructor to call another constructor in a constructor in the same class, thus simplifying the code:

  1. #include <iostream>
  2. class Base {
  3. public:
  4. int value1;
  5. int value2;
  6. Base() {
  7. value1 = 1;
  8. }
  9. Base(int value) : Base() { // delegate Base() constructor
  10. value2 = value;
  11. }
  12. };
  13. int main() {
  14. Base b(2);
  15. std::cout << b.value1 << std::endl;
  16. std::cout << b.value2 << std::endl;
  17. }

Inheritance constructor

In traditional C++, constructors need to pass arguments one by one if they need inheritance, which leads to inefficiency. C++11 introduces the concept of inheritance constructors using the keyword using:

  1. #include <iostream>
  2. class Base {
  3. public:
  4. int value1;
  5. int value2;
  6. Base() {
  7. value1 = 1;
  8. }
  9. Base(int value) : Base() { // delegate Base() constructor
  10. value2 = value;
  11. }
  12. };
  13. class Subclass : public Base {
  14. public:
  15. using Base::Base; // inhereit constructor
  16. };
  17. int main() {
  18. Subclass s(3);
  19. std::cout << s.value1 << std::endl;
  20. std::cout << s.value2 << std::endl;
  21. }

Explicit virtual function overwrite

In traditional C++, it is often prone to accidentally overloading virtual functions. E.g:

  1. struct Base {
  2. virtual void foo();
  3. };
  4. struct SubClass: Base {
  5. void foo();
  6. };

SubClass::foo may not be a programmer trying to overload a virtual function, just adding a function with the same name. Another possible scenario is that when the virtual function of the base class is deleted, the subclass owns the old function and no longer overloads the virtual function and turns it into a normal class method, which has catastrophic consequences.

C++11 introduces the two keywords override and final to prevent this from happening.

override

When overriding a virtual function, introducing the override keyword will explicitly tell the compiler to overload, and the compiler will check if the base function has such a virtual function, otherwise it will not compile:

  1. struct Base {
  2. virtual void foo(int);
  3. };
  4. struct SubClass: Base {
  5. virtual void foo(int) override; // legal
  6. virtual void foo(float) override; // illegal, no virtual function in super class
  7. };

final

final is to prevent the class from being continued to inherit and to terminate the virtual function to continue to be overloaded.

  1. struct Base {
  2. virtual void foo() final;
  3. };
  4. struct SubClass1 final: Base {
  5. }; // legal
  6. struct SubClass2 : SubClass1 {
  7. }; // illegal, SubClass1 has final
  8. struct SubClass3: Base {
  9. void foo(); // illegal, foo has final
  10. };

Explicit delete default function

In traditional C++, if the programmer does not provide it, the compiler will default to generating default constructors, copy constructs, assignment operators, and destructors for the object. In addition, C++ also defines operators such as new delete for all classes. This part of the function can be overridden when the programmer needs it.

This raises some requirements: the ability to accurately control the generation of default functions cannot be controlled. For example, when copying a class is prohibited, the copy constructor and the assignment operator must be declared as private. Trying to use these undefined functions will result in compilation or link errors, which is a very unconventional way.

Also, the default constructor generated by the compiler cannot exist at the same time as the user-defined constructor. If the user defines any constructor, the compiler will no longer generate the default constructor, but sometimes we want to have both constructors at the same time, which is awkward.

C++11 provides a solution to the above requirements, allowing explicit declarations to take or reject functions that come with the compiler. E.g:

  1. class Magic {
  2. public:
  3. Magic() = default; // explicit let compiler use default constructor
  4. Magic& operator=(const Magic&) = delete; // explicit declare refuse constructor
  5. Magic(int magic_number);
  6. }

Strongly typed enumerations

In traditional C++, enumerated types are not type-safe, and enumerated types are treated as integers, which allows two completely different enumerated types to be directly compared (although the compiler gives the check, but not all) , Even the enumeration value names of different enum types in the same namespace cannot be the same, which is usually not what we want to see.

C++11 introduces an enumeration class and declares it using the syntax of enum class:

  1. enum class new_enum : unsigned int {
  2. value1,
  3. value2,
  4. value3 = 100,
  5. value4 = 100
  6. };

The enumeration thus defined implements type safety. First, it cannot be implicitly converted to an integer, nor can it be compared to integer numbers, and it is even less likely to compare enumerated values of different enumerated types. But if the values specified are the same between the same enumerated values, then you can compare:

  1. if (new_enum::value3 == new_enum::value4) { // true
  2. std::cout << "new_enum::value3 == new_enum::value4" << std::endl;
  3. }

In this syntax, the enumeration type is followed by a colon and a type keyword to specify the type of the enumeration value in the enumeration, which allows us to assign a value to the enumeration (int is used by default when not specified).

And we want to get the value of the enumeration value, we will have to explicitly type conversion, but we can overload the << operator to output, you can collect the following code snippet:

  1. #include <iostream>
  2. template<typename T>
  3. std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e)
  4. {
  5. return stream << static_cast<typename std::underlying_type<T>::type>(e);
  6. }

At this point, the following code will be able to be compiled:

  1. std::cout << new_enum::value3 << std::endl

Conclusion

This section introduces the enhancements to language usability in modern C++, which I believe are the most important features that almost everyone needs to know and use:

  1. auto type derivation
  2. Scope for iteration
  3. Initialization list
  4. Variable parameter template

Exercises

  1. Using structured binding, implement the following functions with just one line of function code:

    1. #include <string>
    2. #include <map>
    3. #include <iostream>
    4. template <typename Key, typename Value, typename F>
    5. void update(std::map<Key, Value>& m, F foo) {
    6. // TODO:
    7. }
    8. int main() {
    9. std::map<std::string, long long int> m {
    10. {"a", 1},
    11. {"b", 2},
    12. {"c", 3}
    13. };
    14. update(m, [](std::string key) {
    15. return std::hash<std::string>{}(key);
    16. });
    17. for (auto&& [key, value] : m)
    18. std::cout << key << ":" << value << std::endl;
    19. }
  2. Try to implement a function for calculating the mean with Fold Expression, allowing any arguments to be passed in.

Refer to the answer see this.

Table of Content | Previous Chapter | Next Chapter: Language Runtime Enhancements

Licenses

Creative Commons License
This work was written by Ou Changkun and licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. The code of this repository is open sourced under the MIT license.