Skip to content

Trivia impact: rare

The Empty any Whose Type Is void

an empty box that still answers a type query

std::any value;

std::cout << value.has_value() << " " << (value.type() == typeid(void))
          << "\n";

Does this compile? What does it print?

Answer
0 1

The any has no contained value, yet its reported type compares equal to void.

Why

[any.observers] specifies that any::type() returns typeid(T) for a contained value of type T, and typeid(void) otherwise. void is a sentinel for the empty state; it does not mean that a void object is stored inside the any. has_value() is still the direct question for whether the box currently contains something.

Where it shows up

Logging and type-erasure infrastructure can use one type_info query for both occupied and empty any objects. Most code should test has_value() or use any_cast, so the sentinel matters mainly to generic introspection code.

Takeaway: an empty std::any reports typeid(void), not an unknown type.

Try it: g++ -std=c++17 main.cpp -o demo && ./demo

Open in Compiler Explorer ↗ Quiz this entry