Noutați

Functional exception-less error handling with C++23’s optional and expected

This post is an updated version of one I made over five years ago, now that everything I talked about is in the standard and implemented in Visual Studio. In software things can go wrong. Sometimes we might expect them to go wrong. Sometimes it’s a surprise. In most cases we want to build in some way of handling these misfortunes. Let’s call them disappointments. std::optional was added in C++17 to provide a new standard way of expressing disappointments and more, and it has been extended in C++23 with a new interface inspired by functional programming. std::optional expresses “either a T or nothing”. C++23 comes with a new type, std::expected which expresses “either the expected T, or some E telling you what went wrong”. This type also comes with that special new functional interface. As of Visual Studio 2022 version 17.6 Preview 3, all of these features are available in our standard library. Armed with an STL implementation you can try yourself, I’m going to exhibit how to use std::optional‘s new interface, and the new std::expected to handle disappointments. One way to express and handle disappointments is exceptions: void pet_cat() { try { auto cat = find_cat(); scratch_behind_ears(cat); } catch (const no_cat_found& err) { //oh no be_sad(); } } There are a myriad of discussions, resources, rants, tirades, and debates about the value of exceptions123456, and I will not repeat them here. Suffice to say that there are cases in which exceptions are not the best tool for the job. For the sake of being uncontroversial, I’ll take the example of disappointments which are expected within reasonable use of an API. The Internet loves cats. Suppose that you and I are involved in the business of producing the cutest images of cats the world has ever seen. We have produced a high-quality C++ library geared towards this sole aim, and we want it to be at the bleeding edge of modern C++. A common operation in feline cutification programs is to locate cats in a given image. How should we express this in our API? One option is exceptions: // Throws no_cat_found if a cat is not found. image_view find_cat (image_view img); This function takes a view of an image and returns a smaller view which contains the first cat it finds. If it does not find a cat, then it throws an exception. If we’re going to be giving this function a million images, half of which do not contain cats, then that’s a lot of exceptions being thrown. In fact, we’re pretty much using exceptions for control flow at that point, which is A Bad Thing™. What we really want to express is a function which either returns a cat if it finds one, or it returns nothing. Enter std::optional. std::optional find_cat (image_view img); std::optional was introduced in C++17 for representing a value which may or may not be present. It is intended to be a vocabulary type — i.e. the canonical choice for expressing some concept in your code. The difference between this signature and the previous one is powerful; we’ve moved the description of what happens on an error from the documentation into the type system. Now it’s impossible for the user to forget to read the docs, because the compiler is reading them for us, […]

Read More

vcpkg 2023.04.15 Release: vcpkg ships in Visual Studio, Xbox triplets, GitHub Actions Cache Support, and More…

The 2023.04.15 release of the vcpkg package manager is available. This blog post summarizes changes from February 25th, 2023 to April 15th, 2023 for the Microsoft/vcpkg, Microsoft/vcpkg-tool, and Microsoft/vcpkg-docs GitHub repos. Some stats for this period: 39 new ports were added to the open-source registry. If you are unfamiliar with the term ‘port’, they are packages that are built from source and are typically C/C++ libraries. 957 updates were made to existing ports. As always, we validate each change to a port by building all other ports that depend on or are depended by the library that is being updated for our nine main triplets. There are now 2,190 total libraries available in the vcpkg public registry. 125 contributors submitted PRs, issues, or participated in discussions in the repo. The main vcpkg repo has over 5,300 forks and 18,400 stars on GitHub.   Notable Changes vcpkg now included with Visual Studio IDE As of Visual Studio 2022 (version 17.6), vcpkg is now added by default for IDE installations that include C++ workloads. Visual Studio users can run vcpkg commands from a Developer Command Prompt for Visual Studio targeting a new version of the IDE – both the ones embedded in the IDE as well as external terminals. You must run vcpkg integrate install to configure the built-in copy of vcpkg as the one for use by the IDE and in order to add enable MSBuild and CMake integration. More details will be shared in a separate blog post (coming soon!).   vcpkg now supports targeting Xbox out of the box with four new community triplets. The appropriate triplet is automatically chosen when using the Gaming.Xbox.*.x64 custom platforms in the Microsoft GDK with Xbox Extensions via the vcpkg integrate functionality. This makes it easy for developers to build open-source dependencies for this platform. Thank you to Chuck Walbourn from the Xbox organization for preparing these triplets. Triplet Description x64-xbox-scarlett Builds DLLs for Xbox Series X|S x64-xbox-scarlett-static Builds static C++ libraries for Xbox Series X|S x64-xbox-xboxone Builds DLLs for Xbox One x64-xbox-xboxone-static Builds static C++ libraries for Xbox One   Another benefit of these new triplets is for open-source library maintainers, who can validate that their code will build against the WINAPI_FAMILY_GAMES partition used on Xbox using only the public Windows SDK. To learn more about the new triplets and how to use them, visit Chuck’s blog post on the topic.   Official vcpkg Tool Release Architecture is Now amd64 vcpkg tool releases on GitHub are now amd64 (was previously x86), as we do not expect many users to prefer x86 going forward. PR: Microsoft/vcpkg-tool#1005   Binary Caching Support for GitHub Actions Cache The vcpkg binary caching feature now works with the GitHub Actions Cache. GitHub Actions Cache allows you to use a REST API to query and manage the cache for repositories in GitHub Actions. PR: Microsoft/vcpkg-tool#836 (thanks @quyykk!)   vcpkg use now stacks with previous use or activate commands (but not vice versa) For artifacts users, we have made the behavior of vcpkg use and vcpkg activate consistent when used multiple times. You can run vcpkg use after previously running vcpkg use on another artifact to enable both artifacts at the same time. You can also run vcpkg use after a previous vcpkg activate to enable all artifacts invoked by […]

Read More

Fill in the ISO C++ Developer Survey

The ISO C++ developer survey runs every year and is a great help to us in prioritizing work based on what the community cares about. It only takes about 10 minutes to complete and closes tomorrow, so please take the time to fill it out.   Sy Brand C++ Developer Advocate, C++ Team

Read More

Documentation for C++20 Ranges

C++20 introduced Ranges to the standard library: a new way of expressing composable transformations on collections of data. This feature adds a huge amount of expressive power and flexibility to C++. As with many concepts in C++, that power comes with new concepts to learn, and some complexity which can be difficult to navigate. One way of taming that complexity is through complete, clear, comprehensive documentation. Christopher Di Bella and Sy Brand (one of the co-authors of this post) presented their ideas for C++ documentation in the era of concepts in their CppCon 2021 talk. Tyler Whitney (the other co-author, and manager of our C++ documentation at Microsoft) has expanded these ideas and exhaustively documented the range adaptors available in the standard library for you. To check it out, go to on Microsoft Learn. In this post, we’ll talk through some of the complexity of using and documenting Ranges, and outline the principles behind the documentation which Tyler has written. But first, a quick introduction to Ranges for those of you who are not familiar with the feature. What are Ranges? At a high level, a range is something that you can iterate over. A range is represented by an iterator that marks the beginning of the range, and a sentinel that marks the end of the range. The sentinel may be the same type as the begin iterator, or it may be different, which lets Ranges support operations which simple iterator pairs can’t. The C++ Standard Library containers such as vector and list are ranges. A range abstracts iterators in a way that simplifies and amplifies your ability to use the Standard Template Library (STL). STL algorithms usually take iterators that point to the portion of the collection that they should operate on. For example, you could sort a vector with std::sort(myVector.begin(), myVector.end());. However, carrying out an algorithm across a range is such a common operation, we’d rather not have to retrieve the begin and end iterators every time. With ranges, you can instead call std::ranges::sort(myVector);. But perhaps the most important benefit of ranges is that you can compose STL algorithms that operate on ranges in a style that’s reminiscent of functional programming. Traditional C++ algorithms don’t compose well. For example, if you wanted to build a vector of squares from the elements in another vector that are divisible by three, you could write something like: std::vector input = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; std::vector intermediate, output; std::copy_if(input.begin(), input.end(), std::back_inserter(intermediate), [](const int i) { return i%3 == 0; }); std::transform(intermediate.begin(), intermediate.end(), std::back_inserter(output), [](const int i) {return i*i; }); With ranges, you can produce a range with the same values without the intermediate vector: // requires /std:c++20 std::vector input = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; auto output = input     | std::views::filter([](const int n) {return n % 3 == 0; })     | std::views::transform([](const int n) {return n * n; }); Besides being easier to read, this code avoids the memory allocation that’s required for the intermediate vector and its contents. It also allows you to compose two operations. In the preceding code, each element that’s divisible by three is combined with an operation to square that element. The pipe (|) symbol chains the operations together and is read […]

Read More

What’s New for CMake Tools 1.14 in VS Code – Test Explorer

The team has been working hard to provide new highly requested capabilities for CMake users. Now, in version 1.14, we have provided a new Test Explorer for using CTest with your CMake projects. This release also features open-source community contributions from users. Thanks for your contributions! Test Explorer One of our most highly-upvoted tickets in the CMake Tools Extension was the request for a Test Explorer for CTest. We are excited to announce that this is now available for users in the latest version of the CMake Tools extension in VS Code. Now, in your CMake projects, you can click the “Run CTest” icon along the bottom status bar or the “Testing” side panel icon to launch the test explorer. When the project is configured, the tests in your CMakeLists.txt will load in the Test Explorer. In the Test Explorer, you can view the detailed state of all your tests and the last results of these test runs. By clicking on the play button, you can run a specific test (or set of tests). Also, by clicking on the debug play button, you can debug these tests. Using the topmost icon, you can view the output of these tests. You can refresh these tests at any time using the refresh icon up top. We are continuing to listen to and work on all feedback we receive on the Test Explorer, so if you have any issues or suggestions, please report them in the Issues section of our GitHub repository. Future Work Next up, we are planning to experiment with the CMake tools user experience settings and implement CMake language services and a CMake Debugger. Is there anything else you’d like to see? Let us know! What do you think? Download the CMake Tools extension for Visual Studio Code and let us know what you think. We would love to see what you contribute to our repo and are active on reviews and collaboration. Comment below or reach us via email at visualcpp@microsoft.com or via Twitter at @VisualC.  

Read More

5 New Posts About C, C++, And Python

Hello C++ Developers. In today’s round-up of recent posts on LearnCPlusPlus.org, we have 5 new C and C++ posts with some very simple examples that can be used with a modern C++ Compiler that supports C++17. We also dabble a little with Python too, just for good measure! Table of Contents Why is Python useful to C++ developers? Do you want to learn more about to create beautiful Python GUI applications? What are the important features of C and C++ programming? What new C++ posts are there today? Learn with examples about C and C++ today Learn what’s new next coming C++ Builder Why is Python useful to C++ developers? Python is one of my latest programming languages that I had to learn. I tried to stay avoid it for a long time – it’s a long story, so hear me out! You may not know, but the first release of TensorFlow, the well-known machine learning library, used C++ as the language. The TensorFlow team moved to Python. Then a ‘Lego Mindstorms course for students’ forced me to learn micro Python 4-5 years ago. Even though in my daily work I specialize in AI areas still I stayed away from using Python too often and my primary programming language is mostly C++ usually with C++ Builder. Python is hugely popular and has some really useful libraries. It is one of the favorite languages of new-generation programmers, including my son ???? Python is simple, and easy to learn, and it’s particularly strong in the field of AI and machine learning (ML). If you are a C++ developer, you might want your users to be able to analyze data with AI modules or frameworks written in the Python language in your applications. Let’s imagine you want the users to carry out a few buttons clicks to do some heavy AI analysis. That way you get the best of both worlds by having the raw speed and power of C++ which can run Python modules and make use of their vast ecosystem of libraries and routines. Do you know, you can use Python language in C++ very easily? This week, we will show how you can integrate your C++ application with the Python language.  Do you want to learn more about to create beautiful Python GUI applications? If you have not visited before you should definitely visit the PythonGUI.org website which is a superb resource with lots of great information, full working examples and a whole host of tips, tricks, and free libraries to help you create gorgeous GUI application with Python. Here’s a sample post from PythonGUI.org about some recent updates about Python4Delphi and the Delphi-Python EcoSystem. Latest updates in Python4Delphi and PythonEnvironments in Delphi-Python EcoSystem What are the important features of C and C++ programming? In the programming world today, Python programming language is very popular – perhaps second only to C++. Python is easy to use, and it is more popular because of support from big companies like Google. One of the areas Python is particularly successful are with libraries and frameworks for AI technology and machine learning. It is a great object-oriented, interpreted, and interactive programming language. Python has very clear syntax. It has modules, classes, exceptions, very high-level dynamic data types, and dynamic typing. There are interfaces to many system calls and libraries, as […]

Read More

The Pros And Cons of The C++ Programming Language

C++ has a reputation for being one of the most efficient and powerful programming languages. It is still incredibly popular in almost all developer surveys despite having been available for over 40 years. Understanding the pros and cons of the C++ programming language can help you decide whether or not it’s right for you and also help you to select the right code editor (IDE) and C++ build tools. In this post, we try to explain the many advantages and the few disadvantages of C++.  Table of Contents What are the pros of the C++ programming language? C++ is a compiler-based programming language C++ is a structured and object oriented programming language The C++ language supports visual 2D, 3D and GUI-based programming Learning the basics of C++ is relatively easy because it is a high-level language A C++ program often has low memory usage and great memory management Portability – the benefits of C++ multi-OS and multi-device features C++ is a multi-paradigm language Scalable programming and data is possible with C++ C++ has efficient memory and CPU/GPU usage and low energy consumption The standardization of C++ There is a large community of C++ developers What are the cons of the C++ programming language? C++ can be hard to learn, and C++ programs can sometimes be very complex It can be difficult to analyze errors in a C++ program The syntax of C++ is very strict, and this can make it less flexible than other languages It is possible for C++ to have platform specific features What are the pros of the C++ programming language? C++ is a compiler-based programming language C++ is a compiler-based programming language that makes it the fastest and one of the most powerful programming languages. This is one of the reasons to use hardware and software algorithms efficiently. In general, there are two types of programming languages: Interpreted and Non-Interpreted (Compiled). All computers work with something called machine code (code that can be directly executed by the computer’s CPU) that tells the computer what to do. This is the most native and fastest code, but it requires writing many lines for even quite simple things and is hard to generalize for all kinds of machines. It’s also not very easy to understand for humans. A Compiler (C or C++ Compiler, etc.) is a computer program that converts a program written in a ‘high level’ programming language such as C++ code into executable machine code. The high-level language looks more like English and is much easier to understand and less complicated. C++ is a structured and object oriented programming language C++ allows developers to use C language which is a structured programming language and it also allows Object Oriented Programming. Object Oriented Programming (OOP) is a way to integrate with objects which can contain data in the form of attributes or properties of objects, and code blocks in the form of methods, and functions of objects. These attributes and methods that belong to the class are generally referred to as class members. Object-Oriented Programming is a good way to work on data and work with functions in memory. Classes and Objects are the best way to work on properties and functions. Object-Oriented Programming has many advantages over procedural programming and it is the most characteristic feature of the visual and modern C++ programming language. The C++ language supports visual 2D, 3D and […]

Read More

Learn About The Powerful Alignment Support Functions Of Modern C++

One of the features of Modern C++ is alignment support which was introduced with the C++11 standard. Most of the alignment support features can be used with modern C++ compilers that support one of the ISO Standards of C++11, C++14, C++17, and C++20. In this post, we explain what is alignment support and how we can use alignas, alignof, std::align, aligned_union, aligned_storage, and aligned_alloc in Modern C++. What is alignment support in modern C++? When we talk about ‘alignment’ in C++ it means a set of hints or instructions that tell the compiler to place the physical representation of data structures and variables in memory so that they line up at specific intervals of bytes – the underlaying digital representation of all data items. Alignment tells the compiler and linker to add additional ‘space’ to a value in memory so that the next object begins ‘nicely’ on a particular memory boundary. This is not an aesthetic behavior like aligning the edges of a stack of playing cards but has some specific practical advantages the contribute to your program’s efficiency. Due to the way the CPU and other logic chips in a computer work, alignment can help create more computationally efficient programs. Think of it in the way you cut a cake – if you use an even number of slices for your cake it’s much easier and quicker to divide it up because you can cut the cake into nice even chunks of two. If you get an odd number of cake slices, it’s a lot harder to work out how big those slices need to be to make sure you don’t have a huge slice of cake left over – or someone gets a tiny slice (or none) and stays hungry! By cutting the cake in half each time you are ‘aligning’ your cake slices evenly and optimally so all cake is efficiently used with no wasted cake. The C++11 standard intends to extend the C++ language and library with alignment-related features, known as alignment support. These alignment features include: The alignment specifier alignas for declarations. The alignof expression to retrieve alignment requirements of a type. Alignment arithmetic by library support (aligned_storage, aligned_union). std::align standard function for pointer alignment at run time. Alignment support in C++ can be found in more detail here in the C++ standards [Note: PDF link]. We also discuss the alignof keyword in this blog post: https://learncplusplus.org/what-is-the-alignof-expression-in-modern-c/. What are the alignment support features in modern C++? One of the features of this alignment support was the introduction of a new keyword alignas which is the alignment specifier. For example, we can apply the alignas alignment specifier to define the minimum block size of data types such as the size of structs. In the following post, we explain how we can use alignas in Modern C++ . What Is The alignas Alignment Specifier In Modern C++? Another feature of this alignment support is the keyword alignof which is used for the alignment requirement of a type. In this post, we explain how we can use alignof in Modern C++ What Is The alignof Expression In Modern C++? C++ alignment support also has a keyword align std::align which is used to get a pointer aligned by the specified alignment for a size in bytes of the buffer. In the next post, we explain how we can use align in Modern C++. How To Use std::align In Modern C++ The keyword align std::aligned_union provides a […]

Read More

Where Is A C++ Compiler Download For Windows App Development

Here is the quick answer: If you are new to C++ and want to compile code for the first time, we recommend you try the free C++ Builder Community Edition for students, beginners, and startups. C++ Builder is the easiest and fastest C and C++ IDE for building anything from simple to professional applications on the Windows, macOS, and mobile operating systems. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. C++ Builder comes with RAD Studio, a powerful, helpful, and intuitive IDE for designing apps, creating, editing, and debugging code, and for packing those apps ready for deployment to your users either directly or via the various app stores. 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 cross-platform UIs. More details about C++ Builder & RAD Studio for the beginners can be found in Official Wiki of Rad Studio. RAD Studio, C++Builder professional editions comes packed full of components and tools to make your applications look great and to ease the inclusion of the most up to date features such as biometric authentication, REST libraries for internet services and APIs, in fact almost anything you can think of. You can prototype and implement your app’s visual design by making use of native widgets and platform-extending features, giving your customers an immersive, intuitive and familiar user experience. Components are small packages of ready-to-use functionality which can be anything from visual controls like edit boxes and calendars, or complex multithreaded interactivity such as modern internet communications, to full-featured commercial quality database connectivity. Having thoroughly tested professionally written components makes for efficient coding and is one of the secrets to rapid application development – hence the name RAD Studio. A productive developer is a happy developer. There is nothing quite so satisfying as producing great code. RAD Studio is designed to make your development experience easier with powerful features like code completion and error insight – tools which turbocharge your ability to write code by offering to complete methods and properties as well as highlighting any errors and giving you advice and tips on what might be wrong. It’s a little like having an intelligent spell checker and grammar assistant for your code! A productive team makes everyone happy, especially the management and customers. C++Builder developers report they can deliver applications from concept to deployment 10x faster than with other tools – and getting to market that much faster means direct value to your company. One part of the vast set of useful libraries we provide is FireDAC: an elegant, highly performant database layer. It provides data connectivity to 17 key databases, and over a hundred other data sources from Twitter to SAP through add-ons. VCL and FMX frameworks include libraries built to make you more productive. For example, no C++ developer enjoys string manipulation using the STL’s std::string methods, or loading data in UTF-8 and converting to wide strings for Windows before modifying a string with the WinAPI. Let’s not even talk std::locale. RAD Studio provides powerful, useful classes for strings, conversions, file IO, streaming, JSON, REST, and anything else you need. The latest version RAD Studio 11 has a customizable Welcome Screen with an […]

Read More

What Is Alignment And constexpr In Modern C++?

Hello C++ Developers. In today’s round-up of recent posts on LearnCPlusPlus.org we examine some of the alignment-related features of Modern C++, known as Alignment Support. These alignment features can be used with a modern C++ Compiler that supports C++11, C++14, C++17, and greater.  When we talk about ‘alignment’ in C++ it means a set of hints or instructions that tell the compiler to place the physical representation of data structures and variables in memory so that they line up at specific intervals of bytes – the underlying digital representation of all data items. Alignment tells the compiler and linker to add additional ‘space’ to a value in memory so that the next object begins ‘nicely’ on a particular memory boundary. This week, we teach you what is Alignment Support, what is alignment in C++, how we can use std::align, alignof, alignas, what is meant by a generalized constant expression (constexpr), and what is a forward Declaration enum enumeration. Before everything, let’s take a look at a recent article by Senior Embarcadero Product Manager David Millington where he discusses what we hope to see next in coming C++ Builder features. Learn what’s new next coming C++ Builder According to David’s post, C++ Builder is aiming to include some amazing features; CLANG v15, support for C++20 and a lot of C++23 features, Win64 primary OS, new code completion, Visual Assist C++ navigation and refactoring, and lots more. What’s Coming for C++Builder: An Amazing Preview Disclaimer: All new features and improvements discussed in posts regarding future versions of RAD Studio are not committed until completed, and GA released. Note also that a few weeks ago, Embarcadero also announced the release of RAD Studio 11 Alexandria Release 3, also known as RAD Studio 11.3, along with Delphi 11.3 and C++Builder 11.3. This release is focused on quality and improvements, building on the great new features in RAD Studio 11 Alexandria three previous releases. What are the important features of the C++11 standard in modern programming? The C++11 standard introduced alignment support as one of the many features of a Modern compiler for the C++ programming language. One of the new features of this support is a new keyword align std::align which is used to get a pointer aligned by the specified alignment for a size in bytes in consider with size of the buffer. In the first post, we explain how we can use align  https://learncplusplus.org/how-to-use-stdalign-in-modern-c/ Another part of Alignment support support is a new keyword alignof which is used for the alignment requirement of a type. In the next post, we explain how we can use alignof in Modern C++. https://learncplusplus.org/what-is-the-alignof-expression-in-modern-c/ In another example to Alignment Support, we can apply the alignas alignment specifier to define the minimum block size of data types such as the size of structs. In the next post, we explain how we can use alignas in Modern C++. https://learncplusplus.org/what-is-the-alignas-alignment-specifier-in-modern-c/ C++ is really awesome programming language that has many options to use variables in a way which can make your C++ App use less memory and app size. In the next post, we explain what are a constant, a constant expression (constexpr) and generalized constant expressions in modern C++. https://learncplusplus.org/what-are-generalized-constant-expressions-constexpr-in-c/ Understanding how to correct declare variables is important in programming, especially in a modern C++ Application. There is an enumeration method that allows you to easily enumerate (count or determine their place in an order) values in variables. In C++, enumeration is very important and widely used. In C++, […]

Read More