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:

  1. 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.
  2. Plugin systems: If you're allowing users to provide their own types in plugins, you won't know the types at compile-time.
  3. 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.
  4. 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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

std::any vs std::variant
What's the difference between std::any and std::variant? When would I use one over the other?
Performance Impact of std::any
Does using std::any have a significant performance impact compared to using concrete types directly?
Storing std::any in a Container
How can I store std::any objects in a container like std::vector?
std::any and Memory Leaks
Can using std::any lead to memory leaks? How can I prevent them?
std::any and Small Object Optimization
Does std::any use small object optimization? If so, how does it work and what are the benefits?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant