45,59 €
Learn to build applications faster and better by leveraging the real power of Boost and C++
This book is for developers looking to improve their knowledge of Boost and who would like to simplify their application development processes. Prior C++ knowledge and basic knowledge of the standard library is assumed.
If you want to take advantage of the real power of Boost and C++ and avoid the confusion about which library to use in which situation, then this book is for you.
Beginning with the basics of Boost C++, you will move on to learn how the Boost libraries simplify application development. You will learn to convert data such as string to numbers, numbers to string, numbers to numbers and more. Managing resources will become a piece of cake. You'll see what kind of work can be done at compile time and what Boost containers can do. You will learn everything for the development of high quality fast and portable applications. Write a program once and then you can use it on Linux, Windows, MacOS, Android operating systems. From manipulating images to graphs, directories, timers, files, networking – everyone will find an interesting topic.
Be sure that knowledge from this book won't get outdated, as more and more Boost libraries become part of the C++ Standard.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 397
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: August 2013
Second edition: August 2017
Production reference: 1280817
ISBN 978-1-78728-224-7
www.packtpub.com
Author
Antony Polukhin
Copy Editor
Charlotte Carneiro
Reviewer
Glen Fernandes
Project Coordinator
Sheejal Shah
Commissioning Editor
Merint Mathew
Proofreader
Safis Editing
Acquisition Editor
Nitin Dasan
Indexer
Rekha Nair
ContentDevelopmentEditor
Sreeja Nair
Graphics
Jason Monteiro
Technical Editor
Surabhi Kulkarni
Production Coordinator
Melwyn D'sa
If you are wondering who is Antony Polukhin and could he be trusted to teach about C++ and Boost libraries, then here are some facts:
Antony Polukhin currently represents Russia in international C++ standardization committee
He is the author of multiple Boost libraries and maintains (keeps an eye on) some of the old Boost libraries
He is a perfectionist: all the source codes from the book are auto tested on multiple platforms using different C++ standards.
But let's start from the beginning.
Antony Polukhinwas born in Russia. As a child, he could speak the Russian and Hungarian languages and learned English at school. Since his school days, he was participating in different mathematics, physics, and chemistry competitions and winning them.
He was accepted into University twice: once for taking part in a city mathematics competition and again for gaining high score in an University's mathematics and physics challenge. In his university life, there was a year when he did not participate in exams at all: he gained A's in all disciplines by writing highly difficult programs for each teacher. He met his future wife in university and graduated with honors.
For more than three years, he worked in a VoIP company developing business logic for a commercial alternative to Asterisc. During those days he started contributing to Boost and became a maintainer of the Boost.LexicalCast library. He also started making translations to Russian for Ubuntu Linux at that time.
Today, he works for Yandex Ltd., helps Russian speaking people with C++ standardization proposals, continues to contribute to the open source and to the C++ language in general. You may find his code in Boost libraries such as Any, Conversion, DLL, LexicalCast, Stacktrace, TypeTraits, Variant, and others.
He has been happily married for more than five years.
Glen Joseph Fernandes has worked at both Intel and Microsoft as a Software Engineer. He is the author of the Boost Align library, a major contributor to the Boost SmartPointers and Boost Core libraries, and has also contributed to several other Boost C++ libraries. He is a contributor to the ISO C++ Standard by authoring proposal papers and defect reports, and even has at least one feature accepted for the upcoming C++20standard (P0674r1: Extending make_shared to Support Arrays). Glen lives with his wife, Caroline, and daughter, Aeryn, in the US, graduated from the University of Sydney in Australia, and, before all that, lived in New Zealand.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787282244.
If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
Starting to Write Your Application
Introduction
Getting configuration options
Getting ready
How to do it...
How it works...
There's more...
See also
Storing any value in a container/variable
Getting ready
How to do it...
How it works...
There's more...
See also
Storing multiple chosen types in a container/variable
Getting ready
How to do it...
How it works...
There's more...
See also
Using a safer way to work with a container that stores multiple chosen types
Getting ready
How to do it...
How it works...
There's more...
See also
Returning a value or flag where there is no value
Getting ready
How to do it...
How it works...
There's more...
See also
Returning an array from a function
Getting ready
How to do it...
How it works...
There's more...
See also
Combining multiple values into one
Getting ready
How to do it...
How it works...
There's more...
See also
Binding and reordering function parameters
Getting ready
How to do it...
How it works...
There's more...
See also
Getting a human-readable type name
Getting ready
How to do it
How it works...
There's more...
See also
Using the C++11 move emulation
Getting ready
How to do it...
How it works...
There's more...
See also
Making a noncopyable class
Getting ready
How to do it...
How it works...
See also
Making a noncopyable but movable class
Getting ready
How to do it...
How it works...
There's more...
See also
Using C++14 and C++11 algorithms
Getting ready
How to do it...
How it works...
There's more...
See also
Managing Resources
Introduction
Managing local pointers to classes that do not leave scope
Getting started
How to do it...
How it works...
There's more...
See also
Reference counting of pointers to classes used across functions
Getting ready
How to do it...
How it works...
There's more...
See also
Managing pointers to arrays that do not leave scope
Getting ready
How to do it...
How it works...
There's more...
See also
Reference counting of pointers to arrays used across functions
Getting ready
How to do it...
How it works...
There's more...
See also
Storing any functional objects in a variable
Getting ready
How to do it...
How it works...
There's more...
See also
Passing function pointer in a variable
Getting ready
How to do it...
How it works...
There's more...
See also
Passing C++11 lambda functions in a variable
Getting ready
How to do it...
There's more...
See also
Containers of pointers
Getting ready
How to do it...
How it works...
There's more...
See also
Do it at scope exit!
Getting ready
How to do it...
How it works...
There's more...
See also
Initializing the base class by the member of the derived class
Getting started
How to do it...
How it works...
There's more...
See also
Converting and Casting
Introduction
Converting strings to numbers
Getting ready
How to do it...
How it works...
There's more...
See also
Converting numbers to strings
Getting ready
How to do it...
How it works...
There's more...
See also
Converting numbers to numbers
Getting ready
How to do it...
How it works...
There's more...
See also
Converting user-defined types to/from strings
How to do it...
How it works...
There's more...
See also
Converting smart pointers
Getting started
How to do it...
How it works...
There's more...
See also
Casting polymorphic objects
Getting started
How to do it...
How it works...
There's more...
See also
Parsing simple input
Getting ready
How to do it...
How it works...
There's more...
See also
Parsing complex input
Getting ready
How to do it...
How it works...
There's more...
See also
Compile-Time Tricks
Introduction
Checking sizes at compile time
Getting ready
How to do it...
How it works...
There's more...
See also
Enabling function template usage for integral types
Getting ready
How to do it...
How it works...
There's more...
See also
Disabling function template usage for real types
Getting ready
How to do it...
How it works...
There's more...
See also
Creating a type from a number
Getting ready
How to do it...
How it works...
There's more...
See also
Implementing a type trait
Getting ready
How to do it...
How it works...
There's more...
See also
Selecting an optimal operator for a template parameter
Getting ready
How to do it...
How it works...
There's more...
See also
Getting a type of expression in C++03
Getting ready
How to do it...
How it works...
There's more...
See also
Multithreading
Introduction
Creating a thread of execution
Getting ready
How to do it...
How it works...
There's more...
See also
Syncing access to a common resource
Getting ready
How to do it...
How it works...
There's more...
See also
Fast access to common resource using atomics
Getting ready
How to do it...
How it works...
There's more...
See also
Creating work_queue class
Getting ready
How to do it...
How it works...
There's more...
See also
Multiple-readers-single-writer lock
Getting ready
How to do it...
How it works...
There's more...
See also
Creating variables that are unique per thread
Getting ready
How to do it...
How it works...
There's more...
See also
Interrupting a thread
Getting ready
How to do it...
How it works...
There's more...
See also
Manipulating a group of threads
Getting ready
How to do it...
How it works...
There's more...
See also
Initializing a shared variable safely
Getting ready
How to do it...
How it works...
There's more..
See also
Locking multiple mutexes
Getting ready
How to do it...
How it works...
There's more...
See also
Manipulating Tasks
Introduction
Before you start
Registering a task for an arbitrary data type processing
Getting ready
How to do it...
How it works...
There's more...
See also
Making timers and processing timer events as tasks
Getting ready
How to do it...
How it works...
There's more...
See also
Network communication as a task
Getting ready
How to do it...
How it works...
There's more...
See also
Accepting incoming connections
Getting ready
How to do it...
How it works...
There's more...
See also
Executing different tasks in parallel
Getting started
How to do it...
How it works...
There's more...
See also
Pipeline tasks processing
Getting ready
How to do it...
How it works...
There's more...
See also
Making a nonblocking barrier
Getting ready
How to do it...
How it works...
There's more...
See also
Storing an exception and making a task from it
Getting ready
How to do it...
How it works...
There's more...
See also
Getting and processing system signals as tasks
Getting ready
How to do it...
How it works...
There is more...
See also
Manipulating Strings
Introduction
Changing cases and case-insensitive comparison
Getting ready
How to do it...
How it works...
There's more...
See also
Matching strings using regular expressions
Getting started
How to do it...
How it works...
There's more...
See also
Searching and replacing strings using regular expressions
Getting ready
How to do it...
How it works...
There's more...
See also
Formatting strings using safe printf-like functions
Getting ready
How to do it...
How it works...
There's more...
See also
Replacing and erasing strings
Getting ready
How to do it...
How it works...
There's more...
See also
Representing a string with two iterators
Getting ready
How to do it...
How it works...
There's more...
See also
Using a reference to string type
Getting ready
How to do it...
How it works...
There's more...
See also
Metaprogramming
Introduction
Using type vector of types
Getting ready
How to do it...
How it works...
There's more...
See also
Manipulating a vector of types
Getting ready
How to do it...
How it works...
There's more...
See also
Getting a function's result type at compile time
Getting ready
How to do it...
How it works...
There's more...
See also
Making a higher-order metafunction
Getting ready
How to do it...
How it works...
There's more...
See also
Evaluating metafunctions lazily
Getting ready
How to do it...
How it works...
There's more...
See also...
Converting all the tuple elements to strings
Getting ready
How to do it...
How it works...
There's more...
See also
Splitting tuples
Getting ready
How to do it...
How it works...
There's more...
See also
Manipulating heterogeneous containers in C++14
Getting ready
How to do it...
How it works...
There's more...
See also
Containers
Introduction
Storing a few elements in a sequence container
Getting ready
How to do it...
How it works...
There's more...
See also
Storing at most N elements in the sequence container
Getting ready
How to do it...
How it works...
There's more...
See also
Comparing strings in an ultra-fast manner
Getting ready
How to do it...
How it works...
There's more...
See also
Using an unordered set and map
Getting ready
How to do it...
How it works...
There's more...
See also
Making a map, where value is also a key
Getting ready
How to do it...
How it works...
There's more...
See also
Using multi-index containers
Getting ready
How to do it...
How it works...
There's more...
See also
Getting benefits of a single linked list and memory pool
Getting ready
How to do it...
How it works...
There's more...
See also
Using flat associative containers
Getting ready
How to do it...
How it works...
There's more...
See also
Gathering Platform and Compiler Information
Introduction
Detecting an OS and compiler
Getting ready
How to do it...
How it works...
There's more...
See also
Detecting int128 support
Getting ready
How to do it...
How it works...
There's more...
See also
Detecting and bypassing disabled RTTI
Getting ready
How to do it...
How it works...
There's more...
See also
Writing metafunctions using simpler methods
Getting ready
How to do it...
How it works...
There's more...
See also
Reducing code size and increasing performance of user-defined types (UDTs) in C++11
Getting ready
How to do it...
How it works...
There's more...
See also
The portable way to export and import functions and classes
Getting ready
How to do it...
How it works...
There's more...
See also
Detecting the Boost version and getting latest features
Getting ready
How to do it...
How it works...
There's more...
See also
Working with the System
Introduction
Listing files in a directory
Getting ready
How to do it...
How it works...
There's more...
See also
Erasing and creating files and directories
Getting ready
How to do it...
How it works...
There's more...
See also
Writing and using plugins
Getting ready
How to do it...
How it works...
There's more...
See also
Getting backtrace – current call sequence
Getting started
How to do it...
How it works...
There's more...
See also
Passing data quickly from one process to another
Getting ready
How to do it...
How it works...
There's more...
See also
Syncing interprocess communications
Getting ready
How to do it...
How it works...
There's more...
See also
Using pointers in a shared memory
Getting ready
How to do it...
How it works...
There's more...
See also
The fastest way to read files
Getting ready
How to do it...
How it works...
There's more...
See also
Coroutines - saving the state and postponing the execution
Getting ready
How to do it...
How it works...
There's more...
See also
Scratching the Tip of the Iceberg
Introduction
Working with graphs
Getting ready
How to do it...
How it works...
There's more...
See also
Visualizing graphs
Getting ready
How to do it...
How it works...
There's more...
See also
Using a true random number generator
Getting started
How to do it...
How it works...
There's more...
See also
Using portable math functions
Getting ready
How to do it...
How it works...
There's more...
See also
Writing test cases
Getting ready
How to do it...
How it works...
There's more...
See also
Combining multiple test cases in one test module
Getting ready
How to do it...
How it works...
There's more...
See also
Manipulating images
Getting ready
How to do it...
How it works...
There's more...
See also
If you want to take advantage of the real power of Boost and C++ and avoid the confusion about which library to use in which situation, then this book is for you. Beginning with the basics of Boost C++, you will move on to learn how the Boost libraries simplify application development. You will learn to convert data, such as string to numbers, numbers to string, numbers to numbers, and more. Managing resources will become a piece of cake. You'll see what kind of work can be done at compile time and what Boost containers can do. You will learn everything for the development ofhigh-quality, fast, and portable applications. Write a program once, and then you can use it on Linux, Windows, macOS, and Android operating systems. From manipulating images to graphs, directories, timers, files, and networking, everyone will find an interesting topic.Note that the knowledge from this book won't get outdated, as more and more Boost libraries become part of the C++ Standard.
Chapter 1, Starting to Write Your Application, tells you about libraries for everyday use. We'll see how to get configuration options from different sources and what can be cooked up using some of the data types introduced by Boost library authors.
Chapter 2, Managing Resources, deals with data types, introduced by the Boost libraries, mostly focusing on working with pointers. We'll see how to easily manage resources, and how to use a data type capable of storing any functional objects, functions, and lambda expressions. After reading this chapter, your code will become more reliable, and memory leaks will become history.
Chapter 3, Converting and Casting, describes how to convert strings, numbers, and user-defined types to each other, how to safely cast polymorphic types, and how to write small and large parsers right inside the C++ source files. Multiple ways of converting data for everyday use and for rare cases are covered.
Chapter 4, Compile-Time Tricks, describes some basic examples of Boost libraries can be used in compile-time checking for tuning algorithms, and in other metaprogramming tasks. Understanding Boost sources and other Boost-like libraries is impossible without it.
Chapter 5, Multithreading, focuses on the basics of multithreaded programming and all of the stuff connected with them.
Chapter 6, Manipulating Tasks, shows calling the functional object a task. The main idea of this chapter is that we can split all the processing, computations, and interactions into functors (tasks) and process each of those tasks almost independently. Moreover, we may not block on some slow operations (such as receiving data from a socket or waiting for a time-out), but instead provide a callback task and continue working with other tasks. Once the OS finishes the slow operation, our callback will be executed.
Chapter 7, Manipulating Strings, shows different aspects of changing, searching, and representing strings. We'll see how some common string-related tasks can be easily done using the Boost libraries. It addresses very common string manipulation tasks.
Chapter 8, Metaprogramming, presents some cool and hard-to-understand metaprogramming methods. In this chapter, we'll go deeper and see how multiple types can be packed into a single tuple-like type. We'll make functions to manipulate collections of types, we'll see how types of compile-time collections can be changed, and how compile-time tricks can be mixed with runtime.
Chapter 9, Containers, is about boost containers and the things directly connected with them. This chapter provides information about the Boost classes that can be used in everyday programming, which will make your code much faster and the development of new applications easier.
Chapter 10, Gathering Platform and Compiler Information, describes different helper macros used to detect compiler, platform, and Boost features--macros that are widely used across boost libraries and that are essential for writing portable code that is able to work with any compiler flags.
Chapter 11, Working with the System, provides a closer look at the filesystem and how to create and delete files. We'll see how data can be passed between different system processes, how to read files at the maximum speed, and how to perform other tricks.
Chapter 12, Scratching the Tip of the Iceberg, is devoted to some big libraries and to giving you some basics to start with.
You need a modern C++ compiler, Boost libraries (any version will be OK, 1.65 or a more recent version is recommended), and QtCreator/qmake, or just navigate to http://apolukhin.GitHub.io/Boost-Cookbook/ to run and experiment with examples online.
This book is for developers looking to improve their knowledge of Boost and who would like to simplify their application development processes. Prior C++ knowledge and basic knowledge of the standard library is assumed.
In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also). To give clear instructions on how to complete a recipe, we use these sections as follows:
This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on Code
Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://GitHub.com/PacktPublishing/Boost-Cpp-Application-Development-Cookbook-Second-Edition. We also have other code bundles from our rich catalogue of books and videos available at https://github.com/PacktPublishing/. Check them out!
The source code files of the examples presented in this cookbook are also hosted in the author's GitHub repository. You can visit the author's repository at https://GitHub.com/apolukhin/Boost-Cookbook to obtain the latest version of the code..
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
In this chapter, we will cover:
Getting configuration options
Storing any value in a container/variable
Storing multiple chosen types in a container/variable
Using a safer way to work with a container that stores multiple chosen types
Returning a value or flag where there is no value
Returning an array from a function
Combining multiple values into one
Binding and reordering function parameters
Getting a human-readable type name
Using the C++11 move emulation
Making a noncopyable class
Making a noncopyable but movable class
Using C++14 and C++11 algorithms
Boost is a collection of C++ libraries. Each library has been reviewed by many professional programmers before being accepted by Boost. Libraries are tested on multiple platforms using many compilers and many C++ standard library implementations. While using Boost, you can be sure that you are using one of the most portable, fast, and reliable solutions that is distributed under a license suitable for commercial and open source projects.
Many parts of Boost have been included into C++11, C++14, and C++17. Furthermore, Boost libraries will be included in the next standard of C++. You will find C++ standard-specific notes in each recipe of this book.
Without a long introduction, let's get started!
In this chapter, we will see some recipes for everyday use. We'll see how to get configuration options from different sources and what can be cooked up using some of the data types introduced by Boost library authors.
Take a look at some of the console programs, such as cp in Linux. They all have a fancy help; their input parameters do not depend on any position and have a human-readable syntax. For example:
$ cp --helpUsage: cp [OPTION]... [-T] SOURCE DEST -a, --archive same as -dR --preserve=all -b like --backup but does not accept an argument
You can implement the same functionality for your program in 10 minutes. All you need is the Boost.ProgramOptions library.
Basic knowledge of C++ is all you need for this recipe. Remember that this library is not only a header, so your program has to link against the libboost_program_options library.
This example is pretty simple to understand from code and comments. Running it produces the expected result:
$ ./our_program.exe --apples=100 --oranges=20
Fruits count: 120
Boost's official documentation contains many more examples and tells us about more advanced features of
Boost.ProgramOptions
, such as position-dependent options, nonconventional syntax, and more; this is available at
http://boost.org/libs/program_options
You can modify and run all the examples from this book online at
http://apolukhin.github.io/Boost-Cookbook
We'll be working with the header-only library. The basic knowledge of C++ is all you need for this recipe.
Such flexibility never comes without any cost. Copy constructing, value constructing, copy assigning, and assigning values to instances of boost::any do dynamic memory allocation; all the type casts do RunTime Type Information (RTTI) checks; boost::any uses virtual functions a lot. If you are keen on performance, the next recipe will give you an idea of how to achieve almost the same results without dynamic allocations and RTTI usage.
boost::any makes use of rvalue references but can not be used in constexpr.
The Boost.Any library was accepted into C++17. If your compiler is C++17 compatible and you wish to avoid using Boost for any, just replace the boost namespace with namespace std and include <any> instead of <boost/any.hpp>. Your standard library implementation may work slightly faster if you are storing tiny objects in std::any.
Boost's official documentation may give you some more examples; it can be found at
http://boost.org/libs/any
The
Using a safer way to work with a container that stores multiple chosen types
recipe for more info on the topic
C++03 unions can only hold extremely simple types called Plain Old Data (POD). For example in C++03, you cannot store std::string or std::vector in a union.
Are you aware of the concept of unrestricted unions in C++11? Let me tell you about it briefly. C++11 relaxes requirements for unions, but you have to manage the construction and destruction of non POD types by yourself. You have to call in-place construction/destruction and remember what type is stored in a union. A huge amount of work, isn't it?
Can we have an unrestricted union like variable in C++03 that manages the object lifetime and remembers the type it has?
We'll be working with the header-only library, which is simple to use. Basic knowledge of C++ is all you need for this recipe.
The boost::variant class holds an array of bytes and stores values in that array. The size of the array is determined at compile time by applying sizeof() and functions to get alignment to each of the template types. On assignment, or construction of boost::variant, the previous values are in-place destructed and new values are constructed on top of the byte array, using the placement new.
The Boost.Variant variables usually do not dynamically allocate memory, and they do not require RTTI to be enabled. Boost.Variant is extremely fast and used widely by other Boost libraries. To achieve maximum performance, make sure that there is a simple type in the list of supported types at the first position. boost::variant takes advantage of C++11 rvalue references if they are available on your compiler.
Boost.Variant is part of the C++17 standard. std::variant differs slightly from theboost::variant:
std::variant
is declared in the
<variant>
header file rather than in
<boost.variant.hpp>
std::variant
never ever allocates memory
std::variant
is usable with constexpr
Instead of writing
boost::get<int>(&variable)
, you have to write
std::get_if<int>(&variable)
for
std::variant
std::variant
can not recursively hold itself and misses some other advanced techniques
std::variant
