r/cpp • • Jun 21 '26

Pymetabind: Writing pybind11 bindings with C++26 reflections

https://codeberg.org/bstaletic/pymetabind/
81 Upvotes

26 comments sorted by

View all comments

Show parent comment

1

u/_bstaletic Jun 21 '26 edited Jun 21 '26

Yeah, you could just pass it to std::define_static_string first though in that case.

I could, but I'm trying to minimize my static memory footprint.

That's definitely annoying about the structured bindings propagating the consteval-only-ness. I wonder if that behavior would change with the advent of consteval-only values, which C++26 got a DR for.

Oh, this can easily happen to you without structured bindings. Here's an example:

#include <meta>

struct ouch {
    std::meta::info refl = ^^int;
    int x = 5;
};

int f(int x) { return x; }

int main() {
    constexpr ouch consteval_only;
    return f(consteval_only.x);
}

If you change main() to this:

int main() {
    constexpr ouch consteval_only;
    constexpr int copy = consteval_only.x;
    return f(copy);
}

...then it compiles. Nothing special about structured bindings. They are just how I have learned about this.

 

Another place where this showed up in pymetabind is properties, where my structure looks like this:

struct property {
    const char* name;
    std::meta::info getter;
    std::meta::info setter;
};

Now name becomes "infected" with being consteval-only and I had to do this silly thing:

https://codeberg.org/bstaletic/pymetabind/src/branch/master/include/pymetabind/bind/class.hpp#L140

The name non_escalating_name is indicative of what happens. That whole function, bind_class is neither consteval nor constexpr. It can't be, because it calls pybind11::class_::def_whatever(). So what happens if a non-constexpr function tries to evaluate a consteval-only expression? The expression is treated as "immediate-escalating" and the function becomes implicitly consteval. For a function like bind_class, that makes no sense.

The compiler error is super vague and it took me a while to figure out what is making the call to py::class_::def_property an immediate-escalating expression.