A Month of Writing Reflections-based Code: What have I learned? -- Boris Staletić

Depositphotos_193487310_L.jpgThis post chronicles a month-long experiment using C++26 reflections to automate the generation of pybind11 bindings, blending the promise of modern metaprogramming with real-world complexity. It offers a candid look at what worked beautifully, what fell short, and what future language features could make reflection-driven automation even more powerful.

A Month of Writing Reflections-based Code: What have I learned?

by Boris Staletić

From the article:

I have been trying to automate writing my own pybind11 binding code with the help of C++26 reflections, as implemented by clang-p2996.

There were moments where things went smoothly, but also moments where I missed a feature or two from the world of reflections. Then there is also accidental complexity caused by pybind11 having features which are, at the very least, not friendly for generic binding generation.

Before I begin, a massive thanks to Barry Revzin, Daveed Vandevoorde, Dan Katz, Adam Lach and whoever else worked on bringing Reflections to C++.

Smooth sailing

What we got from the set of reflections papers is awesome. Here's an example of what can be achieved quite easily:

https://godbolt.org/z/jaxT8Ebjf

With some 20 lines of reflections, we can generate bindings that cover:

  • free functions (though not overload sets of free functions - more on that later)

  • structs/classes with

    • a default constructor

    • member functions

    • data members, though always writable from python

You can also see how this easily generalizes to all other kinds of py_class.def_meow(...). Almost... Since C++ does not have "properties" in the python sense, def_property_meow will need special care.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.