CppCon 2019: Marc Gregoire “C++20: What's in it for you?"

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
good morning everyone I hope you had a great conference so far let's kick off the third day with some c++ 20 and what's in it for you first a little bit about myself I'm a software architect from Belgium working for nikon also HD plus plus Microsoft MVP and author of Professional C++ and the C++ standard standard library quick reference books so if you're interested you can pass by the the bookstore and I'm also the founder of the Belgian C++ users group which was started in 2012 and we try to organize three to four events every every year and these are actually quite successful the next one has around 90 attendees which will be in October alright so C++ 20 and one sentence is big there are lots of new features coming and I think it's as big or maybe even bigger as C++ 11 compared to C++ 98 so well let's get started this is the agenda that I will be talking about so first of course we have the four major new features modules ranges go routines and concepts but that's definitely not everything we have a few changes to lambda expressions so there is a slight change how this is captured in a lambda expression we have support for templated lambda expressions we have now pack expansion in alumni captures there are also quite a few changes related to constant expressions so we have support for virtual functions now support for Union trycatch dynamic cast type ID we can do allocations and deallocations and constant expression functions and the stood string and state vector classes are now called expert concurrency changes there are also quite a few that are coming we have now atomic smart pointers we have joining cancelable threads we have a new C++ 20 synchronization library which includes a low level primitive called semaphores we have support for efficiently waiting on atomic variables we have support for latches and barriers and lastly we have an anatomic reference class so these are the the bigger blocks but additionally there is a lot of more functionality that's coming we have designated initializers we have the so called spaceship operator we have support for calendars and time zones in the chrono library we have more functionality to do constant calculations for that we have the pecans evil and Const in it new features we have a sorry we have a text formatting library finally we have some math constants a lot of other stuff so you see there is a lot of new features coming to C++ 20 and some smaller ones are not even on this list since I only have one hour I cannot go into details on every single feature here but for that I refer to other sessions that are focusing on individual features also because I have a lot of material to go through I would like you to ask questions at the end of the presentation there are slight numbers in the lower right corner so if you have a question about a specific slide just remember a slight number for the ends so these are all the new or the majority of the new features additionally we have a couple of new keywords so two of them are concept and requires they are used in the context of concepts then we have caused in it and caused evil these are used in the context of constant expressions we have three four core routines await your return and Co yield and lastly we have char 8d it's surprisingly that was missing from the previous standard before we had charged 16 T and sharp 32 T so now we have the 8 bit version and this one can for example be used to learn work with utf-8 encoded strings additionally there are two new identifiers import and module what's the difference between a keyword and an identifier and identifier the name of these identifiers you can use for your own names but in certain contexts they have a special meaning previously we had also Reddy's such context-aware identifies and these were override and final so now we also have import and module alright so that's the agenda let's get started with modules modules are going to help with distributing your code and to make it easier so what are the advantages we get rid of header files and you are not required anymore to split your interface in the other file and your implementation in a source file everything can go into one file but if you want you can still separate them into inter interface files and implementation files the big difference with other files is that in a module you have to explicitly state which function or which class or which global variable you are exporting everything that is not exported from a module will not be visible from the outside it's completely opposite with where they had a file in a header file everything that is in your header file will be visible from the outside modules don't need this concept from include guards you also don't need to invent unique names if you use the same name in different modules this will not clash with each other modules are only processed once other file is processed every time when you include it modules are processed only once and they will increase your build throughput and a big big feature of module is that preprocessor markers they have no effect on the module so preprocessor macros defined inside your module have no effect on anything on the outside and the opposite as well any preprocessor macro defined outside of your module does not have any effect on your module also lastly the order of how you import modules is not important while the teller files the order can can make an a difference let's have a look at how to create a module to create a module you have to start you can put it in any file you want here I'm putting it in CP pecan dot CPP and to create a module you have to specify export module and then the name of your module in this module I'm just defining one namespace CP pecan and two functions get welcome helper and get welcome and you see the first one is not exported the second one is exported how to consume this module you simply do an import CP pecan and then after that you can use everything that has been exported from my module so in this case from outside my module I don't have access to my get welcome helper so the basic usage of basic way of how to create a module and to consume them are very easy of course there are lots of more complicated things about them but for that I refers to another session unfortunately the C++ tran20 standard does not specify if and how the standard library functionality needs to be exported maybe that's coming in next standard at the moment Visual Studio does make it available as modules so they define five modules at a hex file system memory threading these contained these specific features and then lastly there is a state core module which contains just everything else that is not in the four other modules additionally it is possible to use the import statement to import header files so instead of - includes you just to import iostream this will implicitly turn your iostream header into a module what's the benefit of this is well you have a uniform way of consuming library so can always just use import you don't have to use the hash link loot anymore but also it improves build throughput you can you can think of this feature as some kind of standardized way to work with precompiled header files because this statement import yo stream will turn iostream into a module and compile it once and then reuse it so it's kind of like PCH so that was modules the next big feature is ranges so what is a range it's an object that refers to a sequence or a range of elements so basically it's a replacement for iterator pair of begin and an anti traitor of course it doesn't replace iterator pairs because otherwise we will break all the code there exists so ranges are they exist next to iterator pairs why do we need them or why do we want them they provide for a nicer and easier to read syntax so here I have some data in a vector and I would like to sort that so before C++ 20 or before ranges what you have to do is you have to call the sort algorithm and give it a begin and an iterator with ranges you can just say sort my data so there is much less chance to make an error here now which errors we can make that is you can have mismatch begin and end iterator so you could call sort with begin iterator of one vector and an end iterator of another vector this will not be caught at compile time of course at runtime your program will more than likely crash with ranges you cannot make this kind of mismatch in errors and additionally there are quite a few range adapters that allow you to do lazy computations and I will give you an example of that in a couple of slides so first a little bit more about the three core components of ranges you have views actions and algorithms views they adapt a specific range but they do it lazily so they only do calculations at the moment when you're iterating over your range they don't own anything and they cannot modify any element in your range actions on the other end they are eagerly evaluated and they are modifying your range and then third one all algorithms all standard library algorithms are accept an iterator range now except an iterator pair so they now accept a range and the nice thing about views and action is that you can chain them using the pipe character so let's look at an example I've some data here a vector of integers and I would like to remove all the old elements so what I do is I take my my my vector data and I pipe it through a view and i remove all the elements that are pods next I'll pipe I pipe it to a transform view which will transform all my integers into strings the result of this is if I now iterate over my my my results here then you see I have a vector of 2 4 6 8 10 which are now strings and not integers anymore all of this was lazily executed so just by writing this line out the result equal data and so on this doesn't compute anything it's only when I'm iterating over my result at that point the evaluations are performed actions they can also be chained here I have some again some vector of integers and I'm piping them through a sort action and two unique action and these are actually modifying my data and they're happily having they are appearing eagerly another example here is to show you the power of lazy evaluations so what I'm doing here is I create a view of integers which starts at 1 so this is basically creating something wrong with my pointer so this is basically creating an infinite sequence of integers next piping it to a transformation and I'm calculating the square of of my infinite sequence and finally I take only the 10 first elements and this this range I pass to accumulate so that's ranges next go routines what is a goroutine hold it in as a function that's easy it's a function which has one of the following four key words in it either go away to go return go yield or the range based for Co awaits loop what does go away to it suspends the evaluation of my function wherever I am in the function it suspends it at that moment it gives control back to the caller and later on you can jump back into or resume your quarry to be routine at the moment where you suspended it go return that's the way how you return from a core routine you cannot just use the return keyword you have to use co-routine echo return and go heald's commute returns a value to the color of my my function and then suspends the execution of my core routine another later stage you can jump back or resume back my high-quality what can you use them for well you can use them to implement generators or use them for writing asynchronous i/o libraries do some lazy computations they are also very useful for writing event-driven applications so that's that's all nice unfortunately the C++ trend this term that it contains all the necessary low-level things to make co-routines work but the standard library doesn't really include any helper classes for you yet so if you want these kind of generators or asynchronous i/o you will have to write it yourself or use a third-party library that has implemented it for you so for example Visual C++ comes with an experimental generator it's in the state experimental namespace so let's have a look at how you could use that here I have a function it's actually a quality because inside my body I'm using coil yield it will return a generator and it accepts a start value and a number of values the body of my core routine is simply iterating a number of times and on each iteration it's eco yielding the value for that iteration and it's also outputting the current time so how to use this it's simple you just call get sequence generator you store it somewhere here gem and then you can just use for example a range based for loop to iterate over all the elements in the generator if I run this then so my mail function will will iterate or or will vary for the first element in my my my sequence and then it will output it to the screen and I wait for the user to press any key and when the user press presses the key then my core routine is resumed exactly at the at the moment rarely where we stopped where we suspended it last time so if you look at the output so if I wait a few seconds and press Enter you see the timing you see that my karate was really suspended for half a minute and then continue to do execute all right let's go routines concepts that's another big feature and that's used in the context of templates templates so basically with concepts you can attach requirements to your template types and what is a requirement it's some kind of predicate that is evaluated at compile time so it doesn't have any impact at runtime and you can do quite a lot with these predicates so we'll give a couple of examples of these here is a simple one I'm defining a concept incremental for a type T and what is incremental if something is incremental if I can call either the prefix or the postfix plus plus operator ponens so that's the way how you how you specify it how to use it it's also very easy if you want a function template foo and you want your T to be incremental you can just specify instead of type name you can specify I want an incremental increment ability or you can use this syntax so you keep using the type lay empty and you say requires incremental of T Y the second syntax is necessary I will show you in in the next example this is another way of saying the same thing you can put a requires at the end of your function signature and finally I think this one is the shortest a way to specify this you can just say incremental auto and this will also this is some kind of syntactic sugar so my foo is still a template function a function templates here is an example of a more complicated concept so this was what this concept requires is that my tea has a method called size which returns something that is convertible to a size T so that is the syntax you say X dot size should be compatible and the result of this thing has to be convertible to a size T combining concepts is possible as follows so here I have an again my foo function templates I will type type name T and now I'm requiring that this should be incremental and decremental so this is a syntax are you can do it of course you can also define a second or another concept here I'm defining an incremental concept and I specify that it should be incremental and decrement though and of course once you have that concept it's easy to use here is one example how to use it in this case the this the C++ 20 standard just defined quite a whole collection of of standard concepts so you have these things as derived from convertible to sort ball module and so on in a previous standard dish were using Pascal casing so now they are using that the standard naming convention what what do you concept help with did they help with error messages so if you have done some more complicated template programming you know if you make a small mistake somewhere then you get pages and pages of errors and it's very hard to read this with concepts that will will be greatly improved for example if I call my function template foo with some objects or with some something that's not incremental then the compiler will say clearly cannot call foo with bar because the concept incremental load bar was not satisfied so this will help a lot when you do template programming what changes have been done to lambda expressions first if you want to capture this you have to do it explicitly before if you is this this kind of capture you would capture this implicitly now that's not possible and that's not allowed anymore you need to be explicit about it next you can use the you're familiar template syntax with with long expressions so you can use this type name T and so on why let's look at a couple of motivations why we would like to do this suppose you have a generic lambda it accepts a parameter out of X and I'm assuming this is a factor and I would like to know the type of elements that is inside in my vector so for that I have to use the deco type keyword and type name and it's it's pretty cumbersome with C++ 20 you can just turn this into or you can just use a template syntax and you can define it as follows and you don't need any cryptic tackle type statements anymore similarly if you want to retrieve the type of a parameter for example it because you want to call something some static method on it or or something like that before you have to do something like this again you have the deckle type but you also have to use decay to make sure you get the right type out of it and once you have that then you can for example call a static function or get a nested alias out of it let C++ 20 again that's not necessary anymore you just turn it into a into a template with long expression perfect forward forwarding was possible before but again we have the deckle type there in C++ 20 it's more easily understandable so before a simple capture followed by an ellipsis was a back expansion this is valid C++ 17 syntax what was not valid is the following so I have an initialization captured followed by an ellipsis this was not developed in C++ 17 in C++ 20 this is now legal syntax constant expression changes so now it's allowed to use called expert on virtual functions additionally expert function can now include dynamic cast they can use type by these they can do a dynamic memory allocation de-allocation they can change the active number of a union which was not allowed before and they can contain try-catch blocks what I still not allowed this a constructor function is not allowed to contain throw statements and why was this last part added so because c + + 20 + C + + 20 the state vector and stood string are now cost expert and to be able to make them post expert you need to be able to use try catch blocks so yeah I already mentioned it's the string and state vector are now completely cost expert and this is a first step towards a future support for cost exper reflection in a you know in a future standards concurrency changes so of course we have shared British is this thread safe well it depends how you look at it yes the control book manipulations or the reference count manipulation that is thread saves you so we are sure that only one your object is guaranteed to be deleted only once but accessing the data is of course not thread safe so you have to do it yourself can you make a thread safe yes of course you can use a mutex and protects your your data yourself you can use the global or the free atomic operation functions should such as atomic load atomic store and so on of course that's error-prone because you have to make sure you always use these free functions now we C++ 20 we have atomic share put an atomic weak Peter of course internally they might still use a mutex but as a user you don't care and C++ 20 makes these free non-member atomic operations for share Twitter they make them deprecated let's look at a quick example here this is taken from the paper from herb Sutter this is a concurrent stack implementation or part of it you see here I've an atomic shared pointer as a member and inside the codes I'm doing stuff like dot loads and dot compare exchange week and so on in in before C++ 20 you would have to use a normal shared point not an atomic share point and then you have to make sure that's that you always use things like atomic load do so the free functions and atomic compare exchange week so you always have to use the free functions but even if you don't use a free function you do not get a compilation error it will get of course problems at runtime with the atomic with a new atomic share point you cannot make these mistakes anymore C++ 20 has support for joining and cancelable threats they are defined in the your standard thread header and they are called stood a threat so they they support something called cooperative cancellation so another thread can ask your thread to cancel but it's cooperative so in your threads you have to periodically check if you need to abort your execution or continue something else the J thread they automatically join in a destructor so they ask the thread two to stop gracefully and then they join so they wait or block until the threat has finished executing I'll give an example on the in a few slides canceling threads there are a few things for this you have a stop token the stop token is used by the thread itself to actively check if the thread should be cancelled or not it's compatible with condition variable Eddy so a thread can be waiting on a condition variable or can be waiting at the same time can be waiting for a stop request and so if if either of the two is signaled then your thread wakes up a stop source is is used on the other side so a stop source is used to actually ask another trend to cancel and finally there is something called a stop callback which you can register and which will be called whenever someone requests a threat to stop let's look at an example here I have a function this is good for a pre C++ 20 so let's say C++ 17 what is doing it's creating a threads a local threat object starts running it and then it needs to do something else or you have to be careful with stood threat so if stewed red is destroyed or well for example if you go outside the scope of its function and you're stood threat is still ongoing we're still joinable then your whole process will be terminated so that's why there is this complicated try-catch logic for handling any exceptions that are thrown in my do something else because if that happens I need to catch all the exceptions I need to wait for my alert for my job thread to finish and then I need to read through the exception and of course in the in a normal case also I need to wait for my thread to finish so there's quite a lot of overheads for something that is should be simple now in C++ 20 you can simply write it like this which created a thread instead of a thread and then just do something else so you see there is no try-catch block anymore there are no manual John coils calls if the J tread is destroyed either because an exception was thrown or because you normally exit your scope then the J try to structure will wait for Mike Ladd to finish and then continue okay so how do we cancel a threat I said it's cooperative cancellation so the thread needs to query from time to time if it needs to continue or stop and how to do it is as follows the first parameter of a thread function that you pass to J threads is actually a stop token so then inside the body of your thread you can periodically check if the tops token has been signals so if stop was requested and if that's the case you can you should cancel your threads if you don't need to stop talkin you can create a jet also with a thread function without the stop token s first parameter so basically J thread can be a drop-in replacement for your for the state and then of course someone else in another thread can say something like job dot requests took to terminate the threads same a force it's a new primitive that is added to C++ 20 and basically a semaphore it's very low-level but it can be used to implement all kinds of other synchronous a synchronization concepts like latches barriers I'll come back to these mutexes and so on there are two types you have a counting semaphore and you have a binary semaphore binary semaphore every semaphore as a number of swats which can be empty or which can be filled a binary semaphore audience one slot which can be empty or filled so binary semaphore is perfect for implementing a mutex for example efficient waiting on atomic variables so now you can wait for an atomic object to be changed and it will be notified by another function by another thread so you have these functions wait notify one notify all and of course that's more more can be more performant and pulling if your atomic variable has changed latches and barriers that's new in C++ 20 what is the latch it's a coordination point you construct the latch with a number of threads that you want to arrive at a lodge for example at say 3 then threads are blocking at that point until 3 threads have arrived at that's at the latch and at that moment Alexis signaled and all the threads are allowed to continue barrier is a low is a bit similar but it works in phases so a barrier is constructed with a number of threads that you want to arrive but also a number of phases so on each phase all threads are blocking until a specific specified number of threads arrive at the barrier at which points all the threads are allowed to continue but first a phase completion callback is executed the thread counter is reset all the threads are allowed to continue and the next phase is started atomic ref it's a atomic reference so they allow you to do atomic operations on atomic objects I'm not going deeper in on this one so these were the kind of bigger features with there is a lot of more functionality so let's look at designated initializers so if I have a structure like this which contains an integer and a string if I want to construct an instance of this data structure I can now initialize it as follows I can explicitly state I would like to initialize the a string number with hello your designated initializers they have to be in the right order they have to be in the same order as the world they are in your structure spaceship operator everybody calls the spaceship operator with officially it's called the 3 Way comparison operator basically it's a bit similar to the old c style ster string compare which returns either minus 1 0 or 1 so it doesn't just return your boolean it returns you whether something is smaller equal or larger than another element so usually the common case is you want a set of operators a set of comparison operators to compare an object of type X with an object of type Y so usually this is all all you need to do you just specify X operator and you say default so we also compiler to to implement all 6 comparison operators you see that I specify specified out to as a return type you can be more specific about your return type depending on on the kind of comparisons that you need so if if you can compare for less than that means you can have an ordering otherwise you you're talking about equality and also if in your case a equals B implies F a equals F B if that's true then are talking about the strong ordering or strong equality that's not true you're talking about a week ordering or a week equality so let's have a look at a concrete example here I've a class point with just two data members and int x and y so in C++ 17 if I would like to support all six comparison operators I would have to write I would have to write all of them out I have to write these six functions in c++ xx I can replace all the Reds code with one single green line and I can even ask the compiler do it for me with equal default thus C++ 20 standard library has support for this spaceship operator in all standard classes to vector string map and so on and if you look at the death of the standard document here is an small part of the definition of a vector and you see all the red lines have been replaced by a single green line initializers in c++ 17 they added support for initializers for switch switch statements so basically you have a switch statement you can initialize some variable here and then switch on this value similarly in c++ 17 you could have an initializer for an if statement but what was missing was an initializer for range based for loop so in c++ 20 we can now have this kind of initializers for range based for loops not type template parameters in in the past there were quite a lot of restrictions on long type template parameters for example string literals were not allowed C+ C++ 20 relaxes these restrictions they are not completely gone but they're relaxed quite a lot now what this allows us now is to have string literals as non type template parameters so let's look at a quick example here I have a function template and I can call this by specifying a string literal as my non type template parameters Morcom a more concrete example is the compile time regular expression library so here you can create a much object and you specify the regular expression that you would like to use as a string literal for an on type template parameters and this means that my regular expression can be parsed and can be constructed at compile time so that it will be no runtime overhead for constructing my regular expression object itself there are two new attributes and C++ 20 likely and unlikely they allow you to help the compiler optimizers to say which branch will be you think will be more likely to be used on another one something small the rural library has six has been extended quite a lot so now there is full support for calendars and time zones at the moment only the Gregorian calendar is supported but you can you can write your own calendars that are there that are compatible with with the chrono library let's have a look how to use it if you want to create a year for example you have two ways you can just define you can construct a year or you can use a user-defined little similar for months you can learn two ways to create a month for a day as well how to create a full day full date sorry so you can define it again several ways you can use this handy shorthand notation you can also do something like this here I'm saying I would like to create a date which is the third Monday of September 2019 we have a couple of new duration types before we had seconds minutes hours now we also have days weeks months and years and you can convert of course between them for example here I construct a weeks and I initialize it with one week I can convert this to days and of course the result will be seven if you do something similar for years and months for example you take one year and you want to convert it to days we will actually get something like 365.2425 days because it needs to keep it's an average length over here and similar for a month if you convert convert a month to a day you will get exactly 1/12 over a year which is thirty point four three six eight seven five additionally previously we have the system clock we had the study clock and we had to hire a resolution clock now we have four more clocks we have a UTC clock tie clock GPS clock and a file cook they are very specific so I'm not going into details they have some very specific features like some of them include leap seconds some of them don't include leap seconds the tie clock for example it started in in 58 it was offset at 10 seconds ahead of UTC so these are very specific looks for for your use there are a few new system clock related type aliases so we have system time which is basically a time point for a system clock and based on that there are two other type alias six seconds and six days let's look at an example here I'm creating a date 18th of September 2019 and I'm converting this into a time point and I can do the opposite if I have a time point I can't convert the deck into a date I can also construct a combination of a date at a time this is the way how you can do it so here I'm creating a date which is 18 of September 2019 and I would like to construct 9 o'clock 35 minutes 10 seconds in the morning this is a UTC this is a UTC time that I constructed and then we have the second big part that is new in the krona library that is converted for time zones so if I have my UTC time here created T I can convert this into that the Denver time zone similarly I can say that I have a local time in Denver for example the third Wednesday of September 2019 9/11 the morning and then convert it to the time zone for Denver or you can just ask for the current local time so you say take the current zone take the current time and and return me that out putting a date is very similar it's very easy you can just stream it to an i/o stream next feature stood span it's defined in the span header and it provides you a view over some continuous data it does not own anything it will never do any allocations the allocation nothing it's very similar to string view which was introduced in C++ 17 so similar rest as this string view it's recommended to pass a span as high value because it's very cheap to copy well it does not support this stride so it's really a continuous view over some data there are two two types dynamic size and fixed size so here I have an example where I have some area of data and I create a fixed size span of 42 integers I can drop the 42 in which case this will become a dynamic sized span if I specify the wrong size I specify 50 instead of 42 then I get a compilation error and finally you can also dynamics I spend by specifying a pointer and collect a spend support a couple of features so of course that's full support for iterators you can ask for a beginning iterator and iterator and so on you can ask for the first element the last element you can ask for a sub span of the first X elements or the last XL X elements or you can ask for a sub span in the middle of your your view all of that is possible next feature is features testing macros they allow you to verify if your compiler and your standard library has support for certain features so there are language feature tests macros like here you can check if your compiler support binary literals or if it supports a new char 8d type similarly there are standard library features test macros that you can use to check if your standard library implementation supports concepts ranges scope lock and so on here's a quick example I can check if if if my compiler has the optional header file if it does I can include it and then I can double check if my if that optional header file is actually really implementing the standard library optional class and if that's the case I can I can do something version is a new header file that is standardized so basically this allows us your compiler vendors to to give you some information so meta information like like the version number of your compiler the release date some copyright notice anything like this additionally if you include the version header file it will automatically include all the standard library feature test macros immediate functions so before we had Const expert you can define a cost expert function because you would like that to be evaluated at compile time but this was just a hint to the compiler so it might be executed at compile time but if it's not possible at compile time it will silently drop back and we'll do it at runtime so here is an example I have a function inch to millimeter define Tuscon expert if I call this thing with polls double then everything is fine everything will be calculated at at compile time and the result is a single constant however if I call it with a dynamic inch variable so it's just a double not a constable this will compile fine however it will of course not be at compile time it will be done at runtime if you don't want this you can define a cost eval function also called immediate functions so basically you just replace the cost expert keyword with cost evil now if I call it with my cost double everything is still fine of course everything is calculated at compile time and if I try to call it with mine on calls double then I actually will get a compilation error so it caused eval you're sure that that function will always be executed at compile time and never at the runtime Const init everybody knows about the static initialization order Fiasco so if you have variables with static duration and dynamic initializes well that's only fine behavior you have no idea in which order they will be initialized if you have static variables with constant initializes then everything is fine however for someone reading your code it's not always easy to know that static image that constant initializers are being used and of dynamic initializers so for this the new keyword cost unit can be used and that actually forces constant initialization so it's very easy for someone that is reading your code to see that there is constant initialization happening and not dynamic one let's look at an example you have a function that returns me a string as a constant char star can I have another another function get string which is a constant expression that either it turns me a string literal or calls my my other function based on a parameter that I passed to it if I don't define a static variable and I use the cost in it keywords in this case when I pass through everything is constant and this will be fine if I pass false this would not be this would trigger dynamic initialization but because of the constant keywords that I'm using this will actually be a compilation error so you cannot have any undefined behavior here a small new feature is for class enumerations before class enumerations if you want to access the values of the enumerator you always have to specify the name of the enumerator now you can do something like this you can say using enum and then you can drop these these qualifiers text formatting there is a new text formatting library it replaces the iostream library for printf the iostream up tuna was recommended because of its safety and extensibility on the other hand printf it's not safe not extensible but it's easier to read because you don't have this string of insertion operators so it's it's more fluent to read plus it's nice to have a separation of your formatting string and the arguments that you would like to be injected into your formatting string state format is a combination of both so it's safe and extensible it's also easy to read because it's not in a series of insertion operators and it also just separates your formatting string and and your arguments here is a simple example yeah so the result of this is just hello CPP con 2019 so what does the library support it's extensible its support positional arguments it supports local specific and local independence formatting and you have better control for alignment you have you can left right and centre aligned you can basically it's very easy to go if you have already printf statements it's very easy to convert them to state format it can be almost literally and almost automatically be translated between the two as I said format supports left right and centre alignment while printf only supports left and right let's look at an example here I have a string CPP con 2019 I would like to format it in a field which is 31 characters long the heads means I would like to Center the string and I would like to use an equal sign as fill character so this is the result it's extensible as I said before and if you have a user defined type and you would like to be able to use it to its data formats what you have to do is you have to write a specialization for the state for matter class template and this one in this one you have to implement parts and format methods as I said we have support for positional arguments and that's very useful in the context of localizing your application so if you're translating strings so here I have a string string blah blah blah has so many characters if I would like to translate that to Dutch I could say it like this I say five characters long is text blah blah so you see that the string and the number of characters is reversed in Dutch so then you specify it with with numbers so the one here will be replaced by the the second argument that I pass and the zero will be replaced by the first argument that I pass this sounds all very nice with what about performance well performing is very important so let's have a look here is a benchmark of some some specific good if I if I do some formatting with s printf it's around 800 nano seconds compared to Ostrom and to string the s printf is of course the fastest one if we add format or format to to the mix you actually see that the new new text formatting libraries are actually much faster almost double as fast as the old s printf so there is actually no reason anymore to keep using the SPF the difference between format and format - is that format will return you will create a new string and return that to you while format - will store the result in pre-allocated buffer that you pass to it finally there is a header called numbers we now finally have some mad constants like pi e and so on so now these are standardized they live in the students namespace stood source location to use this it's in the source location header file and this one actually represents information about your source code like line column file in first name basically they replace the underscore underscore file underscore underscore underscore line and so on this kind of macros and you can construct one using source location currents this is very useful if you want to lock something so here I have a function log info with two parameters I have the the text that I would like the law and the second parameter is a source location which I'm giving a default default value namely source location colon colon currents the nice thing about this is that the evaluation of source location current is actually done at the call site it's not done inside my lock info function so at the call site so at this point where I'm calling lock info here source location current is evaluated so when I then output the filename and the line I actually get the line of of the call site so this is pretty pretty useful in C++ seventeen we got support for the no discard attribute now you can add a string explaining the reason why someone should not discard your return value for here for example I'm returning some void star data of course you shouldn't do it but this is for my example and you can say something like no discard ignoring the return value will result in a memory leak bit operations there is a new header file called bits and these provides some free or global non-member functions to operate on bits so what you can do is you can rotate bits left or right you can count the number of zero bits in the beginning or at the end you can count the number of one bits in the beginning or the end or you can count the total number of one bits in a bit in a string of bits here is a quick example so what I'm doing is I have a I've some data here and I would like to rotate it left by by two bits and then I would like to store the result in a bit set and the last example here just counts the number of one bits that are in my in my data there are quite a few smaller things just quickly go over them like URF now start with an ant with four basic strings and string views we have contains so before if you want to know if something is in if some element is inside a map or a set for example you would have to use find and then compare the result with an iterator or you can use the or you could use count and see if it's equal or non not equal to zero now in c++ 20 you can just call a function that clearly states you in turn so you just want to see if my map contains the elements do some small changes that the methods remove remove if and unique for both lists and forward lists they have now a different return type they actually return a size type instead of a void and this is the number of elements that have been removed and finally we have a shift left and a shift right algorithm in the algorithm header files to allow you to shift elements in a range left or right and two more midpoint allows you to calculate the midpoint of two numbers and we have a function to help you with doing linear interpolation and finally there is one new execution policy called an sequence policy and this one allows for parallel algorithms to be vectorized before we had policies to tell an algorithm to two parallel eyes or to paralyze and vector eyes but now you can say that you want all a vectorization and all parallel parallelization and that's it that's a quick overview of everything that's for most of this new and C++ 20 again I cannot go into all the details of every little feature but there are quite a lot of other sessions that go deeper in on specific features that's it any questions I've two minutes left [Applause] hi you mentioned that Sita's pasta is just as big as possible eben in terms of new features which level we had this issue that it took years for the compilers to catch up after the specification do you predict that this will be a similar case with just pasta money no actually a lot of these feature are already available in in one or more compilers or often protected by some compilation flag because it's still experimental and since the standard is not finalized yet there might still be changes so for example if you want to use the co-routines with visual studio you have to specify the slash awaits compiler switch but so for example Visual Studio already supports goroutines modules concepts the other compilers I don't know by heart but they also supports a lot of features already so I definitely don't expect it to take years actually expect towards the end of next year or when the final easiest alert is ratified that most compilers will be up to date already so thank you my question would be the lambda captured the disc capture it needs to be explicit now isn't it a breaking change yes yeah I'm not sure about the reasoning why this was done so maybe we should ask someone from a standard committee thank you question regarding a slide 83 that is four months sorry I have a question about slide 83 this format okay 83 this one yes more or less is the question is with all the problems that we are doing printf if I am wrong specifying the parameter in the string will I have a compile time error or run time it's a type safe so yes you will get a completion time compile time and if you pass the wrong parliament's okay thank you thank you all right thank you [Applause]
Info
Channel: CppCon
Views: 14,910
Rating: undefined out of 5
Keywords: Marc Gregoire, CppCon 2019, Computer Science (Field), + C (Programming Language), Bash Films, conference video recording services, conference recording services, nationwide conference recording services, conference videography services, conference video recording, conference filming services, conference services, conference recording, event videographers, capture presentation slides, record presentation slides, event video recording, video services
Id: Y652wQqbYEI
Channel Id: undefined
Length: 61min 1sec (3661 seconds)
Published: Thu Oct 10 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.