[clang] [Clang] Add support for GCC bound member functions extension (PR #135649)

Zhihao Yuan via cfe-commits cfe-commits at lists.llvm.org
Tue Apr 22 16:28:01 PDT 2025


lichray wrote:

> Perhaps we could provide a builtin function that takes an object pointer and a pointer-to-member-function and returns a devirtualized pointer-to-member-function (or returns the original PMF if it wasn't a pointer to a virtual function)? Unlike the GCC extension, that kind of interface can actually work in general.

I suggest viewing the demands at the same time and taking a leveled approach:

1. invoking base implementation via a handle
2. saving a snapshot of a pending virtual call (delegate)
3. resolve virtual call on one object, apply the results on other objects

Each level is less safe than the previous one. 1 slightly troubles Liskov substitution, 2 doesn't work before the object establishes the runtime type [(in a constructor)](https://discourse.llvm.org/t/rfc-implement-gcc-bound-pmf-in-clang/85951/5?u=lichray), and 3 can apply the call to objects without such a runtime type.

1 is addressed by [p2825](https://wg21.link/p2825).

C++26 `std::function_ref` (with `nontype<pmf>`) can address 2 at the cost of a thunk, usually optimized by sibling call optimization, and safe to use, but you can argue that "simply" assigning from the bit pattern of a C++Builder `__closure` object may just be what user wants.

The dynamic portion of GCC's bound method can address 3, but the feature can also be deemed a building block of `__closure`.

Imagine that you can evaluate `p->mem_fn`, literally a pending virtual call, and get a struct of two members, this will allow the use of structured binding:

```cpp
auto [bpf, pobj] = p->mem_fn;
```

Then, to fulfill 3, we only need a way to package the components back into such a struct to substitute the `pobj` with a pointer to a different object:

```cpp
auto rebound_method = decltype(p->mem_fn){ bpf, pother };
rebound_method();
```

This option is explored by C folks in [n2862](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2862.pdf). In which paper, the rebinding procedure is done by the `wide_set_context` API.

https://github.com/llvm/llvm-project/pull/135649


More information about the cfe-commits mailing list