You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We have found that a very common pattern for event handlers is to capture a weak reference into a lambda, and in the event handler, try to upgrade the weak reference to a strong one, and if so, do some work:
We propose extending the existing delegate constructors to permit a winrt::weak_ref + lambda (or std::weak_ptr + lambda), which simplifies the above to
We have found that a very common pattern for event handlers is
to capture a weak reference into a lambda, and in the event handler,
try to upgrade the weak reference to a strong one, and if so, do some work:
```cpp
widget.Closed([weak = get_weak(), data](auto&& sender, auto&& args)
{
if (auto strongThis = weak.get())
{
strongThis->do_all_the_things(data);
}
});
```
This commit extends the existing delegate constructors to permit a
`winrt::weak_ref` + lambda (or `std::weak_ptr` + lambda), which
simplifies the above to
```cpp
widget.Closed({ get_weak(), [this, data](auto&& sender, auto&& args)
{
do_all_the_things(data);
} });
```
## Implementation notes
A lambda and pointer to member function are hard to distinguish
in a template parameter list. In theory, we could use SFINAE or
partial specialization, but a simpler solution is to distinguish
the two inside the body of the constructor, via
`std::is_member_function_pointer_v`.
The `com_ptr` and `shared_ptr` variants of the test were
unified, since I found myself editing two nearly identical tests.
Fixesmicrosoft#1371
Version
2.0.230706.1
Summary
We have found that a very common pattern for event handlers is to capture a weak reference into a lambda, and in the event handler, try to upgrade the weak reference to a strong one, and if so, do some work:
We propose extending the existing delegate constructors to permit a
winrt::weak_ref
+ lambda (orstd::weak_ptr
+ lambda), which simplifies the above toReproducible example
No response
Expected behavior
No response
Actual behavior
No response
Additional comments
No response
The text was updated successfully, but these errors were encountered: