When to Use Dynamic Types in C++
The lesson mentions dynamic typing should be rare in C++. When is it appropriate to use void pointers or std::any
?
Dynamic typing goes against C++'s philosophy of strong static typing, so it should indeed be used sparingly. However, there are situations where the flexibility is necessary:
- Interfacing with dynamically-typed languages: If you're writing a Python interpreter in C++, for example, you'll need to represent Python's dynamic types.
- Plugin systems: If you're allowing users to provide their own types in plugins, you won't know the types at compile-time.
- Heterogeneous containers: If you need to store objects of differing types in a single container, std::any can be a good fit. A common example is a JSON value, which could be a string, number, boolean, array, or object.
- Communication between systems: If you're passing messages between different processes or across a network, the type might not be known to the receiver.
However, even in these cases, try to constrain the use of dynamic typing as much as possible. Use templates, inheritance, or variant where you can. Reserve void* and std::any for when the type truly cannot be known at compile time.
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