Void Pointers and std::any

Storing std::any in a Container

How can I store std::any objects in a container like std::vector?

Illustration representing computer hardware

You can store std::any objects in a container just like you would any other type. Here's an example with std::vector:

#include <any>
#include <iostream>
#include <string>
#include <vector>

int main() {
  std::vector<std::any> vec;

  vec.push_back(42);
  vec.push_back("Hello");
  vec.push_back(3.14);

  for (const auto& item : vec) {
    if (item.type() == typeid(int)) {
      std::cout << "int: " << std::any_cast<
        int>(item) << '\n';
    } else if (item.type() == typeid(const char*)) {
      std::cout << "string: " << std::any_cast<
        const char*>(item) << '\n';
    } else if (item.type() == typeid(double)) {
      std::cout << "double: " << std::any_cast<
        double>(item) << '\n';
    }
  }
}
Copy codeint: 42
string: Hello
double: 3.14

However, there are a few things to keep in mind:

  1. The std::any objects in the container can hold different types, so you need to use std::any_cast with the correct type to access the value. Getting this wrong will throw a std::bad_any_cast exception.
  2. Checking the type and casting for each element can be cumbersome and inefficient if done frequently. If your use case allows it, consider using a std::variant or a container of a base class type instead.
  3. Copying std::any objects can be expensive, especially if they hold large objects. You might consider using std::unique_ptrstd::any in the container to avoid unnecessary copies, at the cost of more complex memory management.
  4. The type-erasure used by std::any has a runtime cost. If performance is critical, consider alternatives like templates or a custom type-erasure implementation tailored to your specific use case.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved