Fun with C++26 reflection - Keyword Arguments -- Che

reflection-reflection-everywhere.jpgIn this blog post, we’ll explore implementing order-independent keyword arguments for C++ through use of C++26’s proposed reflection features. I stumbled upon this technique while experimenting with reflection a few days ago and thought it might be worthwhile to share, as it nicely showcases just how powerful the proposed reflection features are.

Fun with C++26 reflection - Keyword Arguments

by Che

From the article:

An example implementation of the technique presented in this blog post can be found on GitHub. It can be used with Bloomberg’s experimental P2996 clang fork. If you enjoy these shenanigans, feel free to leave a star. smile

Prior art

Named, labeled or keyword arguments have been proposed many times over the years, but as EWG issue 150 notes: all of these attempts have failed. Here is several past proposals on the topic:

  • n4172 Named arguments
  • p1229 Labelled Parameters
  • p0671 Self-explanatory Function Arguments

Since none of these proposals were accepted, we have to be somewhat creative to get similar functionality in C++. Naturally, there are various approaches to this problem. Below is a short overview of what you can already do without reflection.

Designated initializers

Let’s start with the simplest way to achieve keyword argument-like syntax. C++20 introduced designated initializers for aggregate types, which gives us the initialization syntax Point{.x=42, .y=7}.

In a function call’s argument list the type can potentially be deduced, so we could write foo({.x=2, .y=2}). While this requires extra curly braces and .-prefixes for every member name, syntactically this is almost what we want.

 

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.