Welcome to our deep dive into the world of C++17 and the versatile std::any! This tutorial is designed to help you understand and master the use of std::any, a powerful tool for implementing dynamic polymorphism in your C++ projects.
In simple terms, std::any is a generic type that can hold any type of data, making it an excellent choice for storing values with unknown types. This functionality allows for more dynamic and flexible programming.
To use std::any, first, include the <any> header in your C++ source file:
#include <any>Now, let's create an std::any object and store a simple integer value:
#include <iostream>
#include <any>
int main() {
std::any myAny;
myAny = 42;
std::cout << "The value of myAny is: " << myAny << std::endl;
return 0;
}Output:
The value of myAny is: 42
Retrieving the stored value in an std::any object is done through the use of a type_index object and the std::any_cast function.
#include <iostream>
#include <any>
#include <typeindex>
int main() {
std::any myAny = 42;
std::cout << "The value of myAny is: " << myAny << std::endl;
int value = std::any_cast<int>(myAny);
std::cout << "Retrieved value: " << value << std::endl;
return 0;
}Output:
The value of myAny is: 42
Retrieved value: 42
One of the key advantages of std::any is its ability to store different types of values. Let's demonstrate this by modifying our example to store both an integer and a string:
#include <iostream>
#include <any>
#include <string>
#include <typeindex>
int main() {
std::any myAny;
myAny = 42;
myAny = std::string("Hello, World!");
std::cout << "The value of myAny is: " << myAny << std::endl;
if (myAny.has_value()) {
if (std::any_cast<std::string>(myAny).find("World") != std::string::npos) {
std::cout << "The string contains 'World'." << std::endl;
}
}
return 0;
}Output:
The value of myAny is: Hello, World!
The string contains 'World'
std::any object has a value before retrieving itstd::anystd::any carefully when working with move-only typesWhat is the purpose of using std::any in C++17?
How do you retrieve the stored value in an std::any object?