Void Pointers and std::any

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?

Illustration representing computer hardware

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved