A Journey Into Non-Virtual Polymorphism in C++ - Rudyard Merriam - CppCon 2023

Learn how to effectively use non-virtual polymorphism in C++ to simplify complex code and enhance performance, and discover best practices for managing large datasets.

Key takeaways

When to use non-virtual polymorphism and how to avoid code obfuscation

  • Consider non-virtual polymorphism when you need to implement multiple interfaces dynamically
  • Use template metaprogramming to achieve type erasure and polymorphism

Avoid comparing types using if-else constructs

  • Use variant classes (such as std::variant) instead of if-else statements

Understand std::tuple and its variants

  • Study std::tuple for a “tuple-like” structure with value types
  • Learn std::any, std::visit, and overload resolution to handle variants

Efficiently manage large sums of data

  • Implement size and at methods similar to std::array
  • Note that std::any needs to dynamically allocate memory, possibly leading to performance issues

Cursors and loops are key factors in processing polymorphic operations

  • Learn the basics of iterators before diving into the specifics of CRTP and template metaprogramming
  • Utilize nested loops to iterate through collections; consider std::tuple_element for further optimizations.

These points provide valuable insights on selecting the right tools (such as types, tuples, or polymorphisms) to avoid complex virtual functions and ensure efficiency when coping with large sums of data in computations.