std::any
(C++)
The std::any class in C++ (introduced in C++17) is a type-safe container for single values of any type.
std::any
can hold any type, even types that were not known at the time the program was compiled.
#include <any>
#include <iostream>
#include <string>
int main() {
std::any value = 10; // Store an int
value = std::string("Hello"); // Store a string
try {
std::cout << std::any_cast<std::string>(value) << std::endl; // Retrieve the string
} catch (const std::bad_any_cast& e) {
std::cout << "Bad cast: " << e.what() << std::endl;
}
return 0;
}
- Doesn’t this make it like python?
How does this work under the hood?
I think some sort of memory allocation of void* type, create a copy when the copy assignment operator is called, and copy it into memory.