Storing std::any in a Container

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

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.

Unconstrained Dynamic Types using Void Pointers and std::any

Learn how to use void pointers and std::any to implement unconstrained dynamic types, and understand when they should be used

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

When to Use Dynamic Types in C++
The lesson mentions dynamic typing should be rare in C++. When is it appropriate to use void pointers or std::any?
std::any vs std::variant
What's the difference between std::any and std::variant? When would I use one over the other?
Performance Impact of std::any
Does using std::any have a significant performance impact compared to using concrete types directly?
std::any and Memory Leaks
Can using std::any lead to memory leaks? How can I prevent them?
std::any and Small Object Optimization
Does std::any use small object optimization? If so, how does it work and what are the benefits?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant