program C

How To Use Alias Templates For Traits In C++ 17 and Beyond

One of the great features of C++ is templates, they are parameterized by alias templates in C++11. Then, In C++14 and C++17, they improved C++11’s feature with a number of template aliases whose use simplifies the traits. This feature is called “Alias Templates For Traits” and in this post, we explain what is and alias template and how we can use alias templates with traits. What is a template In C++ ? A template is a simple and a very powerful statement in C++ which defines the operations of a class or function and lets the user apply the same template on different types in those operations. A template defines the operations of a class, a function, it is an alias. For example, we can create an add(a,b) function template as shown below.   template T add (T a, T b) {   return a+b; }   What is a type alias, and an alias template in C++ 11? Type Alias is a term that refers to a previously defined types, alias declaration can be used to declare a name to use as a synonym for a previously declared type. We use using declaration (using-declaration) to declare a type alias, and it is effectively the same as typedef. This can be in block scope, class scope, or namespace scope. Type alias does not introduce a new type and it cannot change the usage or meaning of an existing type name. A type alias declaration is completely the same as typedef declaration. Type alias can be used to create an alias template that can be used as a custom allocator. Type alias which comes after C++11 standard, is used to create an alias template which can be used as a custom allocator. An alias template is an alias that uses a template which refers to a family of types. For example, let’s create a table template which has type, rows and cols parameters. We can create this table (my_table) template as below,   // A Template Example template class my_table { };   We can use this template to create two more alias templates. Here we create a single column (my_column) and a single row (my_row) templates as below,   // Alias Template Example template using my_column = my_table; template using my_row = my_table;   As you see, we have a my_table template and my_column, my_row templates which are alias templates of the my_table template. These templates can be used to with any data types (int, float, char, string, wstring, etc.). Now we can use all the templates to create a table which has rows and columns or a single row or a single column data in a given type. Here is how we can use them,      my_table  table1;    my_column col1;    my_row row1;   What are the alias templates for traits in C++ 14? In C++17, there are alias templates for type traits, they are defined in header and they can be used by using #include . In C++17, they improved C++11’s TransformationTraits feature with a number of template aliases whose use simplifies the traits. According to N3655 paper, “A TransformationTrait modifies a property of a type. It shall be a class template that takes one template-type argument and, optionally, additional arguments that help define the modification. It shall define a nested type1 named type, which shall be a synonym for the modified type.” In […]

Read More

What Is Std::any In C++ 17 And How We Can Use It?

C++17 standard is amazing with a lot of new features, and one of the interesting features was the new type std::any. std::any is a type-safe container to store a single value of any variable type. In this post, we explain std::any in modern C++. What is std::any in C++ 17 ? The any class (std::any) is a new class defined in the  header in C++17 and it is used for any type definition, it is a safe type container for single values that are copy constructible. The std::any is a container type that is used to store any value in it without worrying about the type safety of the variable. It has been designed based on boost::any from the boost library. It is very useful, when you have a variable, and you want to change its type (int to float) on runtime. Here is the simplified syntax for std::any.   std::any ;   Here is a simple definition example. The std::any is a type-safe container that has properties such as has_value(), type(), type().name(); it has modifiers such as emplace, reset, swap; it has bad_any_cast helper class, and it can be used with other methods such as make_any, any_cast, std::swap. How can we use std::any in C++ 17? Here is a simple example how we can use the std::any with different types in C++17 and beyond.   #include   int main() { std::any a;     a = true; // boolean a = 100;  // integer a = 9.81; // double }   In some definitions, we can use literals to define type of the variable, let’s see example below. Is there a full example about how can we use std::any in C++ 17? Here is a full example about std::any that shows different any definitions. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42   #include #include #include #include #include   using namespace std::literals;   int main() { std::any a; std::cout

Read More

What Are The New Fold Expressions In C++ 17

C++17 is another big milestone in the history of C++, it comes with a lot of new features. In C++17, the fold expressions feature is a powerful feature that allows us to fold a parameter pack over a binary operator. Folding Expressions are very useful with variadic templates, and this feature makes template arguments more readable and concise. There are 4 different types of usage and in this post we will give syntax and simple examples about each of them. What are the fold expressions that comes in C++ 17 features? The fold expressions are established after the C++17 standard, they are used to fold (reduce) a parameter pack (fold_pack) over a binary operator (fold_op). The opening and closing parentheses are required in a fold expression. In a folding expression there are 4 parameters, fold_pack is an expression that has parameter pack and no operator fold_op is a binary operator, one of the + – * / % ^ & | ~ = < > > += -= *= /= %= ^= &= |= = == != = && || , .* ->* operators fold_init is an initial expression at the beginning or at the end … is an ellipses symbol that used for arguments There are 4 different syntax in usage, now let’s see them in examples, Is there a simple example about unary right fold expression? Unary right fold expression syntax (since C++17),   ( fold_pack fold_op … )   here is an unary right fold expression example,   template bool URF(Args … args) { return (args && …);  // Unary Right Fold }   Is there a simple example about unary left fold expression? Unary left fold expression syntax (since C++17).   ( … fold_op fold_pack )   here is an unary left fold expression example,   template bool ULF(Args … args) { return (… && args); // Unary Left Fold }   Is there a simple example about binary right fold expression? Binary right fold expression syntax (since C++17).   ( fold_pack fold_op … fold_op fold_init )   here is a binary right fold expression example,   template int BRF(Args&&… args) { return (args + … + 100); // Binary right fold addition }   Is there a simple example about binary left fold expression? Binary left fold expression syntax (since C++17).   ( fold_init fold_op … fold_op fold_pack )   here is a binary left fold expression example,   template int BLF(Args&&… args) { return (1 * … * args); // Binary left fold multiplication }   Is there a full example about fold expressions in C++ 17? Here is a full example about fold expressions in C++17 that has 4 different types in usage. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41   #include   template bool URF(Args … args) { return (args && …);  // Unary Right Fold }   template bool ULF(Args … args) { return (… && args); // Unary Left Fold }   template int BRF(Args&&… args) { return (args + …+ 100); // Binary Right Fold Addition }   template int BLF(Args&&… args) { return (1 *…* args); // Binary left Fold Multiplication […]

Read More

What Are The New Algorithms That Come With C++ 17?

The C++17 standard came with a lot of new features and improvements. One of the features was the math.h library which modernized math operations with the cmath library. The Parallelism Technical Specification adds several new algorithms to the standard C++ library that we can use in C++ Builder 12. These are modernized in the header in the standard library. In this post, we explain the new algorithms that come with C++17. What Are The New Algorithms That Come With C++ 17? C++17 is mostly focused on efficient parallel execution. The new algorithms which support that are available in the usual simple form as well: for_each_n, sample, search, reduce, transform_reduce, exclusive_scan, inclusive_scan, transform_exclusive_scan, transform_inclusive_scan. Now, let’s see some of examples these new algorithms. Iterating ( std::for_each_n ) In C++ 14, we had for_each() to process each element in a given range. In C++17, there is a new std::for_each_n algorithm that executes a function object for each element in the range.    std::for_each_n( first_elemnt, number_of_elements, function)     std::vector vec {47, 12, 3, 9, 5, 21};   for_each_n( vec.begin(), 3,            [](const auto& param)            { std::cout

Read More

What Are The Parallelism Features That Come With C++ 17?

With the C++17 standard, the contents of the Parallelism Technical Specification are added to modern C++, and as a result, make their way into many C++ compilers and IDEs, such as the latest C++ Builder 12. This feature adds new overloads, taking an additional execution policy argument, to many algorithms, as well as entirely new algorithms. Three execution policies are supported, which respectively provide sequential, parallel, and vectorized execution. What is parallel programming (parallelism, parallel computing) ? Parallel computing (Parallel Programming, Parallelism, Parallelization) is a type of computation that applies many calculations or processes simultaneously. Parallel Programming is generally used to solve heavy calculation problems such as real-time analysis of multi-dimensional data, image processing, calculations on fluid mechanics, thermodynamics, and other engineering problems. Parallel Programming is a method that uses multiple computational resources, processors, or processing by groups of servers. Generally, in this type of programming, it takes a problem, breaks it down into a series of smaller steps, delivers instructions, and processors execute the solutions of each part at the same time in different Threads, CPU Cores, CPUs, GPUs. There are many ways to use parallel programming methods and skills, here is an example, What is the development history of parallelism in C++? We can classify the parallel computation level by the level of the hardware technology that supports parallel computation technologies. This depends on your CPU, GPU, Hardware (board, rams, chipsets, …) and Networking technologies (Connection protocols, fibers, WiFi, 5G, etc.) . In other words, this is mostly depends to the distance between computational nodes and its architecture. In the early ages of computers, and computation, some high-processing computer (such as Cray computers) became famous for their vector-processing computers in the 1970s and 1980s. However, vector processors—both as CPUs and as full computer systems—have generally disappeared. Today, we have modern processor instruction sets that have modern vector processing instructions. In addition to these Vector processor examples, we have many Parallelism examples, such as; Multi-core computing, Symmetric multiprocessing, Distributed computing, Cluster computing, Massively parallel computing, Grid computing, Cloud computing, Specialized parallel computers, Reconfigurable computing with field-programmable gate arrays, General-purpose computing on graphics processing units (GPGPU), Application-specific integrated circuits. In 2012, by the improvements in GPUs, representatives from NVIDIA, Microsoft and Intel, independently proposed library approaches to parallel computing in the C++ Standard Library. The authors of these proposals submitted a design in a joint proposal to parallelize the existing standard algorithms library. This proposal was refined under the name of the “Parallelism Technical Specification” over two years. During this process, the Parallelism Technical Specification community, added a lot of feedback from their experimental implementations, since the final version which was published in 2015. As a result, the C++ Standardization Committee had spend three years of experience with the Technical Specification’s design, then all these Parallelism Technical Specifications are added to the C++17 standard, and they are improved in C++20, and still being improved in C++23. (source: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0024r2.html). Parallelism is very important part of programming, because your algorithm can speed up 100-200 times or more (depends of number of CPU cores or GPU cores/transistors). This is why it needs to be improved in every new standard. What is the std::sort algorithm parallelism feature in C++? One of the great examples of parallelism is the std::sort algorithm in modern C++. The Standard Template Library or STL has many algorithms for operations like searching, counting, […]

Read More

What Is The Filesystem Library In Modern C++ 17

In modern C++, the filesystem library allows portable interaction with directories and directory-like structures providing functions such as listing directory contents and moving files. After the C++17 standard, the contents of the Filesystems Technical Specification are now part of modern C++ and are implemented in the filesystem library. What Is the filesystems library in C++ 17? The Filesystem Library is defined in the  header (as a std::filesystem namespace), it provides operations on file systems and their components, such as paths, regular files, and directories. This library allows portable interaction with directories and directory-like structures by using classes and non-member functions. It is modernized well for C++, it is largely modeled on POSIX, and flexible enough to be implementable for different operating systems. After the C++17 standard, the contents of the Filesystems Technical Specification are now part of modern C++ and are implemented in the filesystem library. The filesystem library was previously being used by the boost.filesystem which was published in 2015. In C++17, they merged this library into modern C++. Note that, the boost implementation libraries are still available on more compilers and platforms for many benefits. The filesystem library consists of a lot of file operations (copy, move, permissions), directory operations (listing, iterating, …), and path operations. Some of classes are path, directory_entry, directory_iterator, perms, file_status, … and some of non-member functions in this library are copy, copy_file, current_path, exists, file_size, rename, remove, status, is_directory, is_empty, … Are there some examples of how to use the filesystems library in C++? Here are some examples that can be used with C++17 and standards beyond it, How can I use std::filesystem::current_path in C++ 17? In C++17, we can use std::filesystem::current_path to get current path on runtime. Here is a simple filesystem example in modern C++ that you can get current path.   #include #include   int main() {   std::cout

Read More

How to Use Basic String and Unicode String in Modern C++

In programming, one of the most used variable types are text strings, and they are sometimes really important when storing and retrieving valuable data. It is important to store your data safely in its language and localization. Most programming languages have issues when storing texts and letters. In C++, there is very old well-known string type (arrays of chars) and modern types of std::basic_string types such as std::string, and std::wstring. In addition to these modern string types, C++ Builder has another amazing string feature, UnicodeString. In this post, we explain what a basic string and UnicodeString are in modern C++ and how to use them. What are the string types in C++? In general there are 3 type of alphanumeric string declarations in C++; Array of chars (See Fundamental Types)chars are shaped in ASCII forms which means each character has 1 byte (8 bits) size (that means you have 0 to 255 characters) Basic String (std::basic_string)The basic_string (std::basic_string and std::pmr::basic_string) is a class template that stores and manipulates sequences of alpha numeric string objects (char, w_char,…). A basic string can be used to define string, wstring, u8string, u16string and u32string data types. String or UnicodeStringThe UnicodeString string type is a default String type of RAD Studio, C++ Builder, Delphi that is in UTF-16 format that means characters in UTF-16 may be 2 or 4 bytes. In C++ Builder and Delphi; Char and PChar types are now WideChar and PWideChar, respectively. There is a good article about Unicode in RadStudio. In addition, there were some old string types that we used in C++ Builder and Delphi before, AnsiStringPreviously, String was an alias for AnsiString. For RAD Studio, C++ Builder and Delphi, the format of AnsiString has changed. CodePage and ElemSize fields have been added. This makes the format for AnsiString identical for the new UnicodeString. WideStringWideStrings were previously used for Unicode character data. Its format is essentially the same as the Windows BSTR. WideString is still appropriate for use in COM applications. What is basic_string? The basic_string (std::basic_string and std::pmr::basic_string) is a class template that stores and manipulates sequences of alpha numeric string objects (char, w_char,…). For example, str::string and std::wstring are the data types defined by the std::basic_string. In other words, basic_string is used to define different data_types which means a basic_string is not a string only, it is a namespace for a general string format. A basic string can be used to define string, wstring, u8string, u16string and u32string data types. The basic_string class is dependent neither on the character type nor on the nature of operations on that type. The definitions of the operations are supplied via the Traits template parameter (i.e. a specialization of std::char_traits) or a compatible traits class. The basic_string  stores the elements contiguously. Several string types for common character types are provided by basic string definitions as below. String Type Basic String Definition Standard std::string std::basic_string std::wstring std::basic_string std::u8string std::basic_string (C++20) std::u16string std::basic_string (C++11) std::u32string std::basic_string (C++11) Several string type in std::pmr namespace for common character types are provided by the basic string definitions too. Here are more details about basic string types and their literals. Note that you can use both std::basic_string (std::string, std::wstring, std::u16string, …) and UnicodeString in C++ Builder. Here are more details about basic string types and their literals. What is UnicodeString (String) in C++ Builder? The Unicode standard for UnicodeString provides a unique number for every character (8, 16 or 32 bits) more […]

Read More

When Is The CMath Mathematical Special Functions Header Used in Modern C++?

The math library  in C language is designed to be used in mathematical operations. From the first C language to the latest C++ Builder 12, there have been many changes and improvements in both hardware and software. We were able to use this math.h library in C++ applications. After the C++17 standard, this library is modernized in the cmath library, Functions are declared in  header for compatibility reasons in modern C++. In this post, we explain what are the math.h and cmath libraries. What is the math.h math library in C++? In the early days of computers there was an FPU (Floating Point Unit) in addition to a CPU (Central Processing Unit). While the CPUs were slower in floating point operations (especially in trigonometric functions) FPUs were faster than CPUs in those days. The math library  in the C language is designed to be used in mathematical operations with these FPUs and CPUs. From the first C language to the latest CLANG C++ compiler, there have been many changes and improvements in both hardware and software. We were able to use this math.h library in C++ applications. The math library library functions are declared in math.h header file and it is in the standard library of the C programming language. Most of the functions are trigonometric and basic math functions, and they mostly use floating point numbers such as float, double, or long double variables. Trigonometric functions use radians in angular parameters and all functions take doubles for floating-point arguments unless otherwise specified. In C++ (C++98, C++11, C++14), these C functions were begin used by the same header . For example, if you want to use sin(), cos(), tan(), exp(), log(), and pow() functions you have to add library to the C and C++11, C++14 applications. Note that, some mathematical library functions that operate on integers are instead specified in the  header, such as abs, labs, div, and ldiv. Here is a simple C example using the sin function.   #include #include   int main() { double x = sin(1.0); }   What is the cmath mathematical special functions library in C++? In C++11 and C++14, we were able to use the math.h library in C++ applications. After the C++17 standard, this library is modernized in the cmath library, and functions are declared in  header for compatibility reasons in modern C++, and the is an optional old header to support some old codes. The CMath Mathematical Special Functions Header  defines mathematical functions and symbols in the std namespace, and previous math functions are also included, it may also define them in the global namespace. You have to add a std namespace with using namespace std; or you should use the std:: prefix for each math function. Some of the mathematical special functions are added to the C++17 cmath library header by the contents of the former international standard ISO/IEC 29124:2010 and math.h functions added too. These are only available in namespace std. If you do not use namespace you should add std:: prefix to use these modern math functions. Here is a simple C++ example using the sin function.   #include #include   int main() { double x = std::sin(1.0); }   What is the difference between math.h and cmath in modern C++? The CMath Mathematical Special Functions Header  defines mathematical functions and symbols in the std namespace, and previous math functions are also […]

Read More

What Are The CMath Mathematical Special Functions in Modern C++?

In C++11 and C++14, we were able to use this math.h library in C++ applications. After the C++17 standard, this library modernized math operations with the cmath library. Functions are declared in  header. For compatibility reasons the is an optional alternative to support older code. In this post, we list most of these mathematical functions declared in the header of modern C++. What is cmath mathematical functions library in C++? The CMath Mathematical Special Functions Header  defines mathematical functions and symbols in the std namespace. It includes the previous math functions. It may also define them in the global namespace. You have to add a std namespace using namespace std; or you should use the std:: prefix for each math function. Some of the mathematical special functions are added to the C++17 cmath library header by the contents of the former international standard ISO/IEC 29124:2010 and math.h functions added too. These are only available in namespace std. If you do not use namespace you should add std:: prefix to use these modern math functions. In general, they are mostly double functions and can be slower, but they have more accurate results. For example sin() uses double variables, sinf() uses a float variable (same as C++11, faster, less accurate), while sinl() is used with long double variables (same as C++11, also slower, but more accurate). Here is a simple C++ example using the sin function.   #include #include   int main() { double d = std::sin(1.0); // double float  f = std::sinf(1.0); // float (C++11) long double  l = std::sinl(1.0); // long double (C++11)   }   What are the CMath mathematical special functions in modern C++ 17? There are many new modern mathematical special functions in the C++17 cmath header. Such as functions for associated Laguerre polynomials, elliptic integral of the first kind functions, Cylindrical Bessel functions (of the first kind), Cylindrical Neumann functions, Exponential integral functions, Hermite polynomials functions, Legendre polynomials functions, Laguerre polynomials, Riemann zeta function, and some spherical functions. Here is a list of the CMath special functions. Description double float long double Associated Laguerre polynomials assoc_laguerre assoc_laguerref assoc_laguerrel Associated Legendre polynomials assoc_legendre assoc_legendref assoc_legendrel Beta function beta betaf betal Elliptic integral of the first kind (complete) comp_ellint_1 comp_ellint_1f comp_ellint_1l Elliptic integral of the second kind (complete) comp_ellint_2 comp_ellint_2f comp_ellint_1l Elliptic integral of the third kind (complete) comp_ellint_3 comp_ellint_3f comp_ellint_1l Regular modified cylindrical Bessel functions cyl_bessel_i cyl_bessel_if cyl_bessel_il Cylindrical Bessel functions (of the first kind) cyl_bessel_j cyl_bessel_jf cyl_bessel_jl Irregular modified cylindrical Bessel functions cyl_bessel_k cyl_bessel_kf cyl_bessel_kl Cylindrical Neumann functions cyl_neumann cyl_neumannf cyl_neumannl Elliptic integral of the first kind (incomplete) ellint_1 ellint_1f ellint_1l Elliptic integral of the second kind (incomplete) ellint_2 ellint_2f ellint_2l Elliptic integral of the third kind (incomplete) ellint_3 ellint_3f ellint_3l Exponential integral expint expint expint Hermite polynomials hermite hermitef hermitel Legendre polynomials legendre legendref legendrel Laguerre polynomials laguerre laguerref laguerrel Riemann zeta function riemann_zeta riemann_zetaf riemann_zetal spherical associated Legendre functions sph_legendre sph_legendref sph_legendrel spherical Bessel functions (of the first kind) sph_bessel sph_besself sph_bessell spherical Neumann functions sph_neumann sph_neumannf sph_neumannl Note that, by the C++20 standard, only default names of math functions are used. For example, the laguerre() is used for the float, double and long double versions. For more details about changes in C++17 standard, please see this https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0226r1.pdf C++ Builder is the easiest and fastest C and C++ compiler […]

Read More

What Are The New Rules For Auto Deduction In C++ 17?

The features of C++17 were a big step in the history of C++ and brought a lot of new features. In C++17, there are new auto rules for direct-list-initialization. This feature in C++, changes the rules for auto deduction from a braced-init-list. In this post, we explain what these new rules for auto deduction with examples are. What is auto keyword in C++? The auto keyword arrives with the new features in C++11 and improved in C++17, can be used as a placeholder type specifier (an auto-typed variable), or it can be used in function declaration, or in a structured binding declaration. The auto keyword can be used with other new CLANG standards like C++14, C++17, etc. What are the new rules for auto deduction in C++ 17? In C++17, For copy-list-initialization, the auto deduction will either deduce a std::initializer_list (if the types of entries in the braced-init-list are all identical) or be ill-formed otherwise. Note that, auto a = {1, 2, 3}, b = {1}; remains unchanged and deduces initializer_list. This change is intended as a defect resolution against C++14. Now, let’s see the examples below. Auto deduction from braced-init-list Rule #1 For direct list-initialization: For a braced-init-list with only a single element, the auto deduction will deduce from that entry. In the example below, there is a single member in the braced-init-list, and this is automatically defined as an initializer_list that consists of int members.   auto a = { 30 }; // decltype(a) is std::initializer_list for (auto i : a)  std::cout

Read More