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:
- 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.
- 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.
- 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.
- 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