C++ std::any (C++17)

beginner
11 min

C++ std::any (C++17)

Welcome to our comprehensive guide on using std::any in C++! This powerful feature was introduced in C++17 and is a versatile tool for handling heterogeneous data types. Let's dive right in!

What is std::any? šŸŽÆ

std::any is a template class that allows storing and retrieving values of different data types within a single object. It's like a box that can contain an apple today and an orange tomorrow.

Why use std::any? šŸ’”

  • Type Erasure: std::any eliminates the need for multiple objects to handle different types, making your code cleaner and more efficient.
  • Flexibility: With std::any, you can store any type of data in a single object, making it ideal for generic programming.

How to use std::any? šŸ“

Creating an std::any object

First, let's create an std::any object and store an integer:

cpp
#include <iostream> #include <memory> #include <numeric> int main() { std::any myAny = std::make_integer<int>(42); // Creation and initialization std::cout << "The value is: " << myAny << std::endl; return 0; }

In the code above, we include the necessary headers, create an std::any object called myAny, and initialize it with the value 42 using std::make_integer.

Retrieving the value

To retrieve the stored value, we use the std::any_cast function:

cpp
int value = std::any_cast<int>(myAny); // Retrieving the value std::cout << "The value is: " << value << std::endl;

Checking the type

To check the type of the stored data, we use the std::type_index:

cpp
auto type = myAny.type(); // Get the type if (type == typeid(int)) { std::cout << "The type is int." << std::endl; }

Advanced Example šŸ“

Let's create a simple function that takes an argument of any type and returns its square:

cpp
template <typename T> T square(const std::any& value) { T result = std::any_cast<T>(value); return result * result; }

In the example above, we define a template function square that takes an std::any argument and returns the square of its value. We retrieve the value using std::any_cast, perform the square operation, and return the result.

Quiz

:::quiz Question: What is the output of the following code?

cpp
#include <iostream> #include <memory> #include <numeric> int main() { std::any myAny = std::make_integer<int>(42); std::cout << "The value is: " << myAny << std::endl; std::any myAny2 = std::make_integer<double>(3.14); std::cout << "The value is: " << myAny2 << std::endl; return 0; }

A: The output will be 423.14. B: The output will be 42 and 3.14. C: The output will be an error. Correct: B Explanation: The output will be 42 and 3.14 because std::any can store different types of data in separate objects.