#include
#include
#include
using MyInt = int;
using MyString = std::string;
using MyVector = std::vector;
int main()
{
MyInt x = 123;
MyString s = "Hello World";
MyVector v = { 1, 2, 3, 4, 5 };
}
2 C++14
C++14 is an ISO C++ standard published in 2014. It brings some additions to the language and the standard library, but mainly complements and fixes the C++11 standard. When we say we want to use the C++11 standard, what we actually want is the C++14 standard. Below are some of the new features for C++14.
To compile for C++14, add the -std=c++14 flag to a command-line compilation string if using g++ or clang compiler. In Visual Studio, choose Project / Options / Configuration Properties / C/C++ / Language / C++ Language Standard and choose C++14.
14.1 Binary Literals
Values are represented by literals. So far, we have mentioned three different kinds of binary literals: decimal, hexadecimal, and octal as in the example below:
int main()
{
int x = 10;
int y = 0xA;
int z = 012;
}
These three variables have the same value of 10, represented by different number literals. C++14 standard introduces the fourth kind of integral literals called binary literals. Using binary literals, we can represent the value in its binary form. The literal has a 0b prefix, followed by a sequence of ones and zeros representing a value. To represent the number 10 as a binary literal, we write:
int main()
{
int x = 0b101010;
}
The famous number 42 in binary form would be:
int main()
{
int x = 0b1010;
}
Important to rememberValues are values; they are some sequence of bits and bytes in memory. What can be different is the value representation. There are decimal, hexadecimal, octal, and binary representations of the value. These different forms of the same thing can be relevant to us humans. To a machine, it is all bits and bytes, transistors, and electrical current.
14.2 Digits Separators
In C++14, we can separate digits with a single quote to make it more readable:
int main()
{
int x =100'000'000;
}
The compiler ignores the quotes. The separators are only here for our benefit, for example, to split a large number into more readable sections.
14.3 Auto for Functions
We can deduce the function type based on the return statement value:
auto myintfn() // integer
{
return 123;
}
auto mydoublefn() // double
{
return 3.14;
}
int main()
{
auto x = myintfn(); // int
auto d = mydoublefn(); // double
}
14.4 Generic Lambdas
We can use auto parameters in lambda functions now. The type of the parameter will be deduced from the value supplied to a lambda function. This is also called a generic lambda :
#include
int main()
{
auto mylambda = [](auto p) {std::cout << "Lambda parameter: " << p << '
'; };
mylambda(123);
mylambda(3.14);
}
14.5 std::make_unique
C++14 introduces a std::make_unique function for creating unique pointers. It is declared inside a header. Prefer this function to raw new operator when creating unique pointers: