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:
Answers to questions are automatically generated and may not have been reviewed.
std::any
Learn how to use void pointers and std::any
to implement unconstrained dynamic types, and understand when they should be used