Programming dev-c++ end FireMonkey FMX ide learn learn

What Are The Elementary String Conversions That Come With C++ 17?

In addition to many beneficial features of C++ 17, there are elementary string conversions introduced in that specification. The std::to_chars() and std::from_chars() are defined in header to do conversions between numeric values to strings or strings to numeric values without considering locale-specific conversions. In this post, we explain the std::to_chars() and std::from_chars() that come with C++17. What Are The Elementary String Conversions That Come With C++ 17 ? What is std::to_chars()? The std::to_chars() is defined in header and is used to convert numeric values into a character string within the given valid range. The std::to_chars() is designed to copy the numeric value into a string buffer, with a given specific format, with the only overhead of making sure that the buffer is big enough. You don’t need to consider locale-specific conversions. Here is the syntax of std::to_chars in C++ 17.   std::to_chars_result  to_chars( char* first, char* last, value, int base = 10 );   Here is a simple example.   std::string str= “abcdefgh”; const int ival = 10001000; const auto con = std::to_chars( str.data(), str.data() + str.size(), ival);   In floating point number conversions, std::chars_format types can be used (i.e. std::chars_format::fixed, std::chars_format::scientific, std::chars_format::general,…) What is std::from_chars()? The std::from_chars() is defined in the header and used to convert the string data in a given range to a value (string to int, string to float operations) if no string characters match the pattern or if the obtained value is not representable in a given type of value, then the value has remains unchanged. The std::from_chars() is a lightweight parser that does not need to create dynamic allocation, and you don’t need to consider locale-specific conversions. Here is the syntax of std::from_chars in C++ 17.   std::from_chars_result from_chars( const char* first, const char* last, &value, int base = 10 );   Here is a simple example.   std::string str= “10001000”; int vali; auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), vali);   Is there a full example to elementary string conversions that comes with C++ 17? Here is a full example about std::to_chars() and std::from_chars() in C++ 17. 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   #include #include #include   int main() { std::string str= “abcdefgh”;   // INT TO CHAR const int ival = 10001000; const auto con = std::to_chars( str.data(), str.data() + str.size(), ival);   std::cout

Read More

What Is The Class Template Variant (std::variant) in C++ 17?

In C++ Builder 12, and modern C++ the std::variant is one of the powerful features that comes with C++17. The std::variant is a discriminated union that we can work with multiple data types. It represents a type-safe union and holds one of its types in definition. What is the class template std::variant in C++ 17? The std::variant is a class template defined in  header that represents a disjoint union (or discriminated union). A value of variant contains one of an A, a B, or a C at any one time. It can be used as a multi-type variable, for example, a variable can be a float, an int, or a string. Here is the template definition since C++17:   template class variant;   Here is a simple example that shows how we can use it.   std::variant myvar; myvar = 100; // int   To get value of a variant we can use std::get (std::variant), here is how we can use it:   std::variant myvar2; myvar2 = std::get(myvar);   std::variant has many useful methods and properties that can be used in modern C++, such as index, valueless_by_exception, emplace, swap, get_if, visit, variant_size, variant_size_v, variant_npos, monostate, std::hash, and operators ( =, ==, !=, , =, ) Is there a full example about the class template variant in C++ 17? Here is an example. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23   #include #include #include   int main() { std::variant myvar;   //myvar = true; // bool myvar = 100; // int     if ( std::holds_alternative(myvar) ) std::cout

Read More

What Is The New std::sample Algorithm In C++ 17?

The C++ 17 standard bring us a lot of useful methods, templates and algorithms. One of the great algorithms is std::sample defined in the header that samples at most n elements uniformly from a given range. In this post, we explain the std::sample algorithm and how we can use it with an mt19937 random generator. What is the std::sample algorithm in C++ 17 and beyond? The std::sample algorithm is defined in header that samples at most n elements uniformly from a given range into the output iterator and random numbers can be generated by using a random number generator function. Generally std::mt19937{} is used as random generator and std::random_device{}() is used random generator device. The std::sample algorithm is defined as a template algorithm in C++17 as shown below.   template SampleIterator sample( PopulationIterator first_in, PopulationIterator last_in,                        SampleIterator output, Distance n, URBG&& function );   Here, first_in and last_in are the iterators that defines range of input. n is number of elements to be sampled into output iterator, function is random number generator function. Is there a full example about the std::sample algorithm in C++ 17 and beyond? Here is a full example about std::sample in C++ 17. 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   #include #include #include #include #include #include   int main() { std::vector vec_in {“This”, “LearnCPlusPlus.org”, “is”, “really”, “amazing”,“!”}; std::vector vec_out;   std::cout

Read More

Everything You Need To Know About The Copy Assignment Operator In C++ Classes

Classes and Objects are part of object-oriented methods and typically provide features such as properties and methods. One of the great features of an object orientated language like C++ is a copy assignment operator that is used with operator= to create a new object from an existing one. In this post, we explain what a copy assignment operator is and its types in usage with some C++ examples. What is a copy assignment operator in C++? The Copy Assignment Operator in a class is a non-template non-static member function that is declared with the operator=. When you create a class or a type that is copy assignable (that you can copy with the = operator symbol), it must have a public copy assignment operator. Here is a simple syntax for the typical declaration of a copy assignment operator which is defaulted: Syntax (Since C++11).   class_name & class_name :: operator= ( const class_name& ) = default;   Here is an example in a class.   Tmyclass& operator=(const Tmyclass& other) = default; // Copy Assignment Operator   Is there a simple example of using the copy assignment operator in C++? The forced copy assignment operator is default in any class declarations. This means you don’t need to declare it as above. Let’s give examples without using it. Let’s give a simple C++ example to copy assignment operator with default option, here is a simple class:   class myclass {   public:   std::string str;   };   Because this is default in any class declaration, and it is automatically declared. This class is same as below.   class myclass {   public:   std::string str;     Tmyclass& operator=(const Tmyclass& other) = default; // Copy Assignment Operator };   And here is how you can use this “=” copy assignment operator with both class examples above.   Tmyclass o1, o2;   o2 = o1; // Using Copy Assignment Operator   now let’s see different usage types in C++, 1. Typical Declaration of A Copy Assignment Operator with Swap 2. Typical Declaration of A Copy Assignment Operator ( No Swap) 3. Forced Copy Assignment Operator 4. Avoiding Implicit Copy Assignment 5. Implicitly-declared copy assignment operator 6. Deleted implicitly declared copy assignment operator 7. Trivial copy assignment operator 8. Eligible copy assignment operator 9. Implicitly-defined copy assignment operator C++ Builder is the easiest and fastest C and C++ compiler and IDE for building simple or professional applications on the Windows operating system. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for UIs. There is a free C++ Builder Community Edition for students, beginners, and startups; it can be downloaded from here. For professional developers, there are Professional, Architect, or Enterprise versions of C++ Builder and there is a trial version you can download from here.

Read More

What Is The New Optional Class Template In C++ 17?

The C++17 standard came with a lot of great features and std::optional was one of the main features of today’s modern C++. std::optional is a class template that is defined in the header and represents either a T value or no value. In this post, we explain, what is optional in modern C++ and how we can use it efficiently. What is the optional class template in C++ 17 and beyond? The std::optional feature is a class template that is defined in the header and represents either a T value or no value (which is signified by the tag type nullopt_t). In some respects, this can be thought of as equivalent to variant, but with a purpose-built interface. Here is the definition of the std::optional class template.   template class optional;   Optional can be used to define any type of variables as below.   std::optional a(5); std::optional b;   An optional variable can be checked by has_value() method if it has a value or not.   if (a.has_value()) { }   Here is another example that has a function with an optional return.   std::optional testopt(std::string s) { if(s.length()==0) return {}; else return s; }   as you see our function may return a string as an option or it may have no return value. A common use case for optional is the return value of a function that may fail. Any instance of optional at any given point in time either contains a value or does not contain a value. If an optionalcontains a value, the value is guaranteed to be allocated as part of the optional object footprint, i.e. no dynamic memory allocation ever takes place. Thus, an optional object models an object, not a pointer, even though operator*() and operator->() are defined. Is there a simple example about the optional class template in C++ 17? Here is a simple example about the std::optional, 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19   #include #include   int main() { std::optional a(5);  // a = 5 std::optional b;   // b has no value   if (a.has_value())         { int z = a.value() + b.value_or(0); std::cout

Read More

What Is basic_string_view And string_view In Modern C++

C++17 had enormous changes in C++ features. One of them was basic_string_view (std::basic_string_view) which is a constant string container that can be used for multiple string declarations. The basic_string_view is a modern way of read-only text definition. It can be used by iterators and other methods of the basic_string_view class. In this post, we explain basic_string_view and its types. What is basic_string_view in modern C++ In the Library Fundamentals Technical Specification (LFTS), The C++ commitee introduced std::basic_string_view, and it was approved for C++17. The basic_string_view (std::basic_string_view) is a class template defined in the header that is used to define a constant string container that can be used to define multiple strings which refers to the contiguous character sequence, and the first element of this sequence position at the zero position. The basic_string_view is a modern way of read-only text definition, it can be used by iterators, and other methods of the basic_string_view class can be used.  Here is the syntax of the basic_string_view:   template class basic_string_view;   We can use different character types in std::basic_string_view types as same as std::basic_string. The std::basic_string_view has 5 different string types, these are, std::string_view, std::wstring_view, std::u8string_view, std::u16string_view, and std::u32string_view. The std::string_view provides read-only access to a string definition with chars as similar to the interface of std::string. In addition to this, we can use std::wstring_view, std::u16string_view, and std::u32string_view in C++17. There is std::u8string_view that is added by the C++20 standards too. Here are the basic_string_types and their features. Type Char Type Definition Standard std::string_view char std::basic_string_view (C++17) std::wstring_view wchar_t std::basic_string_view (C++17) std::u8string_view char8_t std::basic_string_view (C++20) std::u16string_view char16_t std::basic_string_view (C++17) std::u32string_view char32_t std::basic_string_view (C++17) Is there an example about basic_string_view in modern C++ Here is a C++ example that we use std::string_view, std::wsting_view, std::u16string_view, std::u32string_view in C++17. 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   #include #include #include   int main() { const std::string_view  sview = “This is a stringview example”; const std::wstring_view wsview = L“This is a stringview example”; const std::u16string_view u16sview = u“This is a stringview example”; const std::u32string_view u32sview = U“This is a stringview example”;   const std::string_view sviews[]{ “This is “, “LearnCPlusPlus.org “, “and welcome “, “!” };   for ( auto sv : sviews) { std::cout

Read More

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