Whereas std::variant<A,B,C>
can hold an A or B or C,
std::any
can hold (almost) anything!
C++14 | C++17 | C++17 |
---|---|---|
void * v = ...;
if (v != nullptr) {
// hope and pray it is an int:
int i = *reinterpret_cast<int*>(v);
} |
std::any v = ...;
if (v.has_value()) {
// throws if not int
int i = any_cast<int>(v);
} |
std::any v = ...;
if (v.type() == typeid(int)) {
// definitely an int
int i = any_cast<int>(v);
} |
Note: std::any is NOT a template. It can hold any types, and change type at runtime.
C++14 | C++17 |
---|---|
// can hold Circles, Squares, Triangles,...
std::vector<Shape *> shapes; |
// can hold Circles, Squares, Triangles, ints, strings,...
std::vector<any> things; |