San Diego C++ Meetup – Meeting #69

Hello all,

Summary of San Diego C++ Meetup – Meeting session number 69. Took place on December 10 2024.

This is the last session for 2024!

Event link can be found here.

Topics we covered:

  • Modern C++ Programming: A tutorial/training session by Federico Busato.
  • ADL and the  std::swap idiom: Including a mention of  std::ranges::swap(). The discussion covered ADL, anonymous namespaces, and the global namespace, highlighting the subtleties when mixing them.
  • Mapping a runtime value to compile time: More details on this topic are provided below.
  • Variadic templates and fold expressions: Exploring techniques to eliminate duplicate code.
  • Lightning talk by GC: GC’s slide deck on “Stateless Allocators and Memory Resources” can be found here.

How can I map a runtime value to a compile-time value?

This was the main topic. The idea was as follows: given something like:

How can I take a runtime value n and pass it to the function? func<n> would not work since n is not a compile-time value!

The original problem to solve was the following (values are just for the example, it could be anything): for a range [0…5] map to 128, [6…10] map to 256, [11…max] map to 512.

People attending the session immediately suggested using an array/map/hash-map (aka unordered_map). I did not have any material to demonstrate anything with these elements, but before I show the solution presented in the session, let’s try to solve it first with the unordered_map type (since people claim it has O(1) efficiency).

This obviously cannot work. The compiler will complain: “call to non-‘constexpr’ function ’ … “. CE link.

So, what about trying to embed some constants in the “value” part of the unordered_map?

So the problem is, what do we place instead of the ????

What is the actual type? Even if I use integral_constant, which can be used in constant expression contexts, I don’t have a way to provide the type. std::integral_constant<std::size_t, 128> is different from std::integral_constant<std::size_t, 256>.

The next attempt was using Jason Turner’s idea of a “constexpr map.” For reference, here is Jason’s C++ Weekly:

Here is a link to CE trying to get it working. But again, this only works with compile-time inputs. The requirement was runtime inputs!

Let’s take a look at the actual implementation presented in the session. For this, you need to be familiar with:

  • std::lower_bound: Given the values [5, 10, max] and a needle, we need lower_bound to find the correct item among the values. Note that lower_bound is not a must here; we could also use a linear search like find/ find_if.
  • std::integral_constant<>: An important ingredient in the overall solution. This is where we can actually pass a constant to the template NTTP!
  • std::variant<> + std::visit() + overloaded{} idiom: For more information, check out cppreference and cppstories.com, which has tons of great articles on these.

Here is a CE link to the overall solution. Thanks to GC for suggesting constexpr on the return of lower_bound when working with C++20! My solution needed to compile with C++17.

Here is a simple explanation of what’s going on:

We have an array of variants. The std::variant is of type:

Think of it as mapping some number to std::integral_constant<size_t, some_value>.

Given a needle, find the index in the array of variants. We use:

  • lower_bound
  • overloaded{} idiom
  • std::visit to extract the first value in the pair<>

Once we have the result of lower_bound, given the iterator return value, we can compute the index using std::distance(base, iter).

Invoke a call that takes the index. We use the index with the array: arr[n].

Since arr[n] yield a variant type, we can run std::visit, getting the value and extracting the integral_constant, which is the second type in the pair.

Now, we can pass it to an NTTP by calling func<p.second()>(). The magic happens with integral_constant<>! It can be used as an NTTP!

That’s it for this session. I bet there are some other cool ways to achieve something similar!

Thank you for reading!

Kobi

San Diego C++ Meetup #68 – The Art of Writing Efficient Programs – design choices for Performance (Nov 13 2024)

Hello all!

Here is the summary of the last San Diego C++ Meetup, virtual meeting, took place on Wednesday, Nov 13 2024.

Link to the meetup event page here.

Recording uploaded to the San Diego C++ Meetup channel (sdcppmu)

The agenda:

  1. cppquiz fun – C++ Quiz – 297 – std::async, future .wait() vs .get()
  2. Recommending YT channel – “C++Next by Alex Dathskovsky”
  3. The Art of Writing Efficient Programs – chapter 12 – Design choices for Performance.
  4. Tip: transparent comparator/operators.

More details:

First, Alex’s YT channel mentioned above is something you should checkout. It’s fun, short episodes and packed with good information.

We mentioned few Design choices as mentioned in Fedor G. Pikus book: “The Art of Writing Efficient Programs: An advanced programmer’s guide to efficient hardware utilization and compiler optimizations using C++ examples”:

Chapter 12 discuss “Design for Performance”. We mentioned:

  1. Choosing APIs for performance. operator[] vs iterator interface, std::deque as an example to have better performance using iterator vs operator[].
  2. Using std::set<> in conjunction with std::vector<>, using member vs non-member functions.
  3. Lock vs non-lock interfaces, runtime vs Template, policy based classes. Also, using decorators (inheritance in this case).
  4. Redundant get-ters/set-ters and when these are actually could be useful.
  5. 13:34 – we mentioned std::span<>! 🙂
  • Transparent operator – using std::less<> which is like std::less<void>, the benefit of using it, how can it save you from debugging subtle bugs.

This is for this session, thank you for reading!

Kobi

San Diego C++ Meetup – Data Structures and Algorithms with C++ STL (#67)

Hello all,

We had a fun evening on Tuesday October 15th, discussing C++ STL, Data structure and various modern techniques. The inspiration coming from a recently published book by John Farrier:

recording:

San Diego C++ Meetup recording

Event page here.

Hey everyone,

Here’s a quick recap of our discussion:

We kicked things off with cppquiz 167. It’s a tough one but packed with important modern C++ concepts like RValue, LValue, and what happens when you pass an RValue to a function. We also touched on std::move and std::forward. Give it a shot and make sure to read the explanation!

C++ Data Structures and STL:

  • We talked about getters and exposing internal data structures from your class. We also introduced alternatives like iterators and discussed how to write them in different ways.

SFINAE and std::void_t:

  • We covered how SFINAE tweaks the compiler’s function candidate list, mentioned C++20 concepts, and how std::void_t can help. We also discussed type_traits, if constexpr, static_assert(), declval, and how cppinsights.io can be useful.

Allocator Interface:

  • How to use it with STL containers.

std::span<> Example:

  • We went through an example of std::span<>.

Gotchas:

  • Comparing two strings or comparing pointers? Check out the last 2-3 minutes of the recording for the full details!

Book Recommendation:

  • I liked the book, though it was a bit basic for me. However, I think it’s great for newcomers to the language/STL to get familiar with various containers, algorithms, and other parts of the Standard Template Library.

Thanks for reading!

Kobi

San Diego C++ Meetup #66 – Modern CMake for C++

Hello everyone,

Last Tuesday (September 17, 2024), we gathered for the 66th meeting of The San Diego C++ Meetup.

The topic was CMake. Yes, CMake can be fun sometimes! 😊

The inspiration for this session came from the relatively new 2nd edition of “Modern CMake for C++” by Rafal Swidzinski.

First off, the book is fantastic! It’s packed with valuable material that can make your life easier if your build system is CMake. Despite considering myself quite knowledgeable about CMake, I learned a lot from it.

This wasn’t my first time giving a talk on CMake. I’ve had several opportunities in the past, ranging from one-hour to multi-hour sessions. It always feels like there’s so much to cover that even 1, 2, or 4 hours isn’t enough to touch on every aspect of CMake. CMake is extensive, and it’s crucial to understand and use it well. Otherwise, your build system can become difficult to improve, extend, and maintain, leading to a lot of frustration.

When discussing CMake (or any topic in a C++ session), my goal is for everyone to learn something new—at least one thing!

The meetup page link: here

And the recording:

San Diego C++ Meetup recording

BTW – We had an excellent session on July 11, 2023, with Alex Reinking, titled “Modern CMake Best Practices for Library Authors” at the San Diego C++ Meetup. It’s definitely worth watching!

Summary of our discussion:

  • Introduction to the book.
  • CMake’s popularity (based on 2023 surveys).
  • Overview of CMake: its purpose and stages (configuration, generation, and build).
  • Simple CMake files and FetchContent.
  • Generators: what they are and how to write agnostic command lines that work with any generator.
  • CMake Cache file (CMakeCache.txt): using the --force option, cache variables, and debugging/tracing CMake build generation with options like --trace, --log-context, --trace-expand, and --debug-output.
  • Cleaning with the --clean-first option.
  • Targets: what they are and how to build them.
  • Installation: a high-level overview (there’s much more to explore here).
  • Running CMake as a script with the -P option.
  • Brief mentions of CTest/CPack and other tools in the CMake suite.
  • CMakeConfigureLog.yaml (introduced in version 3.26) for advanced debugging of the configure stage.
  • Utility modules included with the CMake package, and projects like cmake-awesome and cmake-modules.
  • Find modules.
  • A slide on important elements of the CMake language (the book has an excellent chapter on this).
  • CLion and CMake: debugging CMake with CLion.

Additional topics covered in the book:

  • Generator expressions
  • Dependency graph and how to print it
  • CMake presets
  • Program analysis tools
  • C++20 modules
  • Testing frameworks
  • Generating documentation

Many thanks to Packtpub for their support providing me the material to review!

That’s it for this session!

Happy CMake-ing!

Kobi

San Diego C++ Meetup #65

Hello everyone,

Super late in writing this summary, can’t believe we are 1 week past the session. I’ve been super busy at work and with Family.

What did we have on the Agenda:

  1. Guo Ci, our guest speaker, presented 2 techniques that are being used to optimize C++ code. The first is doing binary searches with equal_range (in std::ranges and std) and the second is customizing the three-way comparison operator (<=>). Slides: guoci SDCPPMU presentation
  • bio: Guo Ci. Guo is a bioinformatician at the University of Michigan, working in labs doing proteomics and genomics research.
  1. Adding Default Constructor using =default; to your class type.

sdcppmu Youtube recording:

Event page from meetup.com

Summary of the discussions:

  1. From Guo Ci talk – demonstrated techniques related to spaceship/comparison operator
    • Changing order of the non-static data members, changes the default operator<=>
    • usage of std::tie and restoring the required order
    • Transformation of the data members before comparison, using make_tuple and std::cref
    • While float provides partial_ordering, what if we want strong_order?
    • Caveats related to std::tuple’s <=>
    • Synth-three-way
  2. Second item from Guo Ci talk – A more generic equal_range
    • An optimized way to reduce algorithm complexity, running on a sorted array
    • Showed benchmarking comparisons
    • Overview from the slides:

Next part of the meeting talked about “Adding Default Constructor using =default; to your class type”. We compared aggregate changes between 17 and 20. For 20, an aggregate cannot have “user-declared or inherited constructors”. 17 could. So 20 is stricter. Examples in the slides from godbolt.

The last part of the session talked about top level const in function deceleration, why clang-tidy complains and the rational behind it.

Thanks for reading!

Kobi

San Diego C++ Meetup #64 – July 16 2024

Hello all!

Summary of the recent San Diego C++ meetup session, took place Tue, July 16 2024 5PM Pacific Time.

Agenda in this meeting:

  1. New C++ Book – C++ Brain Teasers! – by Anders Schau Knatten – image above.
  2. Discussion on Throwing destructors
  3. Yet another hard to find(?) bug

Meetup event page here.

Recording can be found here:

San Diego C++ #64 Meetup recording

Details:

  1. I introduce “C++ Brain Teasers” book by Anders Schau Knatten. The PragProg page has 3 items that can be accessed. Puzzles 2,3,14. We went over each and discussed it. Super fun book, very recommended! Amazon link if you’d like also the colored printed book.
  2. Throwing destructors Discussion – noexcept and C++11, is it a good idea to throw from destructors? what happens when you aggregate a type with “noexcept(false)” ? How to workaround such issue? What do Core Guidelines say? It triggered lots of good discussions.
  3. And finally, a very hard to find(?) bug related to temporaries and lifetime. I saw it in production code few times in the past few months and wanted to share it with the group. Lots of good discussions here as well!

That’s it for July 2024. Working on the agenda for the next meeting!

Thank you for reading!

Kobi

100 C++ Mistakes and How to Avoid Them – by Rich Yonts – San Diego C++ Meetup #63

This month we hosted Rich Yonts, the author of a Manning publication title (MEAP/Beta) – 100 C++ Mistakes and How to Avoid Them

The recording can be found in our San Diego C++ Meetup channel:

San Diego C++ Meetup #63

The meetup even link can be found here.

About Rich Yonts:

Rich Yonts is a Senior Software Engineer at Teradata and a long-time software engineer using C++, Java, and Python. Rich held a number of technical and leadership roles during his many years at IBM and Sony. As an assistant professor, he has dealt with questions and issues of undergraduate and graduate students learning programming. He has deep experience on large code bases and considers himself both a student and a teacher of C++.

Rich cherry-picked few examples from the book and presented to the group.

Here is the summary of the topics:

  1. The challenges when dealing with old codebase in various companies. i.e. dealing with 98/03 and not beyond that.
  2. Narrowing values, uniform initialization to detect narrowing.
  3. Referring to an uninitialized data member and UB.
  4. Post vs pre increment of type instances.
  5. The fit fall of using setter when class invariant is not checked/violated and how to solve it.
  6. Shallow vs deep copy and how to ensure a deep copy with copy constructor and op=.
  7. The benefit of using the “override” keyword.
  8. Using “=delete” keyword to disable a specific function, vs the old 98/03 “method”.
  9. Variadic Templates.
  10. Using sprintf vs iostream vs std::format.

That’s it for June 2024 session.

Thank you for reading!

Kobi

San Diego C++ Meetup #62

Introducing: “Modern C++ Programming Cookbook” – Master modern C++ including the latest features of C++23 with 140+ practical recipes, Third Edition – By Marius Bancila

Meetup session page: san-diego-cpp

Recording (sdcppmu Youtube Channel):

San Diego C++ meetup #62

I continued using “google meet” where I can share the slides directly from my google drive, record a session, chat with attendances and it works beautifully!

Recent session introduced Marius’ newly published book which is really a good one (as usual :)!

The session started with a warm up, c++quiz Question #287. A bit of a tricky one. If you cannot remember the exact constructor diffs of std::string, you are out of luck 🙁

The main session/talk was on “Implementing the higher-order functions map and fold“. Taken from chapter 3 from the book (just part of the chapter). Oh – and we had a raffle of 3 ebooks!

Minutes:

  1. Map, fold implementation.
  2. Various overloads to support different containers that might behave a bit differently in the way we iterate over the items (std::queue<> is one example).
  3. The difference between the presented fold() and “C++17 fold expressions”.
  4. Composing(composing(composing(functions))) – with many examples.
  5. Fold left/right functions.
  6. Functions as first class citizens. Returning functions and composing a chain of functions.
  7. Overload operator* as a syntactic sugar when composing.

That’s it for this session. Next session should be a really nice one. Working on bringing a new speaker with an interesting topic!

Take care,

Kobi

San Diego C++ Meetup – #61 Apr 16 2024

Hello all,

Yet another summary of our latest session of San Diego C++ Meetup. America’s finest city endorsing America’s favorite language 😉

The meetup page can be found here.

San Diego C++ Meetup #61 recording.

Agenda summary

  1. C++ quiz – Arrays and copies during range-for-loop.
  2. The right auto/auto* – When using auto, and the deduced type is pointer, should we use auto? or auto*. Spoiler – use auto*. But why? This items takes us through the reasoning behind it. Hint – it helps readability and correctness especially with const involved.
  3. Does a default virtual destructor prevent compiler-generated move operations? – Fascinating journey investigating the implication of user defined destructor and move operation, talking about Howard’s famous table. Then – what does it mean in base classes when =default is used for virtual destructor. And finally, what is the best way to understand whether a specific class type is move constructible. Hint – it’s not that easy and straightforward, but we introduced a neat trick.
  4. And finall In-Place Construction for std::any, std::variant and std::optional – this item was inspired by Bartłomiej Filipek C++ Stories blog post.

That’s it for this session. Thank you for reading!

Kobi

San Diego C++ Meetup #60 – March 12 2024

Hello everyone,

San Diego C++ Meetup – 5 Years! 60 meetings! took place Tuesday March 12th 2024.

Here is the link to the meetup.com page.

Recently, I’m moving away from Windows+Teams.

Last session, we used Zoom utilizing Andreas Fertig’s account. Andreas was our guest speaker on Feb 2024.

For March, I tried using Google Meet but I missed the fact that I needed premium “GoogleOne” account and it was too late to add it. I have it now for next sessions. Hence the recording did not work.

No worries, after the meeting I spent ~20 minutes to record myself going over the agenda so we have it on record. Here is the recap:

San Diego C++ meetup session #60 – Recap post session recording

Our Agenda:

1. C++ Quiz
2. What is IILE/IIFE ? Deep dive to some of immediate invocation tricks.
3. Strongly typed syntax – How can we achieve a better, less error prone code? NamedType to the rescue!

More details:

C++Quiz – Question 126 was about Lookup rules. Question 29 was about invoking virtual functions in constructors and destructors (Don’t!), and finally Question 312 was about class/struct inheritance and access specifiers – “would this compile?”

The second part was about Immediately Invoked Lambda/Function Expression(IILE/IIFE). Few tricks, why is it useful, should we use std::invoke and benchmarks using Bartek’s cppstroies blog post.

And finally, we discussed C++ and strong types, user defined string literals and finalized with NamedTyped library example.

That’s if for the 60th session update, thank you for reading!

Kobi

Exploring Polymorphism in C++ – San Diego C++ Meetup Feb 2024

Hello everyone,

We had a special guest speaker on Tuesday, Feb 20th 2024. Andreas Fertig!

This is not Andreas’ first appearance in our Meetup and I was super happy to host him again!

This session went over an interesting and extremely useful information – Runtime vs Compile time polymorphism.

The event page can be found here.

Recording, as usual can be found in the San Diego C++ Meetup Youtube channel.

Exploring Polymorphism in C++: Run-time vs. Compile-time by Andreas Fertig – San Diego C++ meetup

Presentation material can be found in our dropbox location (join the meetup to gain access).

Summary of the material discussed:

  1. Cost of runtime polymorphism.
  2. CRTP as an alternative, lower runtime cost alternative.
  3. Policy based design.
  4. Example of policy – std::unique_ptr and the deleter policy.
  5. std::sort and the sorting policy.
  6. Another example of the Policy based idiom, checked array boundaries with multiple types of handling errors – all with Policy design.

That’s it for this month!

Next time, it’d be our #60 session. Yes! 5 years of San Diego C++ Meetup. We have over 1650 members. We started off on March 2019, with around 70 members!

Thanks for reading,

Kobi

San Diego C++ Meetup #58 – Modern C++ Design, chapter 2

Hello all,

Quick summary on a great Tuesday night on Jan 16 where we went over chapter 2 of Andrei’s A. book – Modern C++ design.

meetup-event link

Recording:

San Diego C++ Meetup sdcppmu Youtube recording

Here is the overall summary of what we went over in this session:

  1. Compile time assertions
  2. Partial template specialization.
  3. Local classes.
  4. Map integral constants to types. Compile time dispatch based on numeric values. Boolean conditions.
  5. Type to type mapping. For overloading and function template partial specialization.
  6. Type selection, based on compile time boolean conditions.
  7. Detect convertibilities and inheritance at compile time.
  8. TypeInfo wrapper over type_info. Value semantic and ordering comparisons.
  9. NullType, EmptyType placeholders classes.
  10. The last part – “TypeTraits template to offer multiple general purpose traits to help us tailor the code to specific categories of types” – as I expected – we did not have time since we were already overtime (around 1hr and 10 mins) but feel free to go over the last 4-5 slides with the type_info and the overall type traits class.

Overall, in the past 2 sessions (Dec 2023, Jan 2024) we showed the power of Templates with the great help of Andrei’s book. As I mentioned, the book is unique and even after 20+ years, still ranked top IMO. The first 2 chapters are the basic building blocks, the pillars for a better understanding of Generic programming. Worth investing time and reading it.

Thank you!

Kobi