[libcxx-commits] [libcxx] [libcxx] Modify `std::__for_each{, _n}` to accept r-values in `__f` (PR #179451)

Connector Switch via libcxx-commits libcxx-commits at lists.llvm.org
Tue Feb 3 08:24:26 PST 2026


================
@@ -17,32 +17,36 @@
 #include <__iterator/segmented_iterator.h>
 #include <__type_traits/invoke.h>
 #include <__type_traits/is_same.h>
+#include <__utility/forward.h>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
 #  pragma GCC system_header
 #endif
 
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
 _LIBCPP_BEGIN_NAMESPACE_STD
 
 template <class _InputIterator, class _Sent, class _Func, class _Proj>
 _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 _InputIterator
-__for_each(_InputIterator __first, _Sent __last, _Func& __func, _Proj& __proj) {
+__for_each(_InputIterator __first, _Sent __last, _Func&& __f, _Proj& __proj) {
 #ifndef _LIBCPP_CXX03_LANG
   if constexpr (using _SpecialAlg =
                     __specialized_algorithm<_Algorithm::__for_each, __iterator_pair<_InputIterator, _Sent>>;
                 _SpecialAlg::__has_algorithm) {
-    _SpecialAlg()(__first, __last, __func, __proj);
+    _SpecialAlg()(__first, __last, std::forward<_Func>(__f), __proj);
----------------
c8ef wrote:

If std::generate is implemented as follows, we can add our test coverage about this.

```
template <class _ForwardIterator, class _Generator>
inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void
generate(_ForwardIterator __first, _ForwardIterator __last, _Generator __gen) {
  using __iter_ref = decltype(*__first);
  __identity i;
  std::__for_each(__first, __last, [&](__iter_ref __element) { std::forward<__iter_ref>(__element) = __gen(); }, i);
}

template <typename T>
class Ref {
private:
  T* ptr;

public:
  Ref(T* p) : ptr(p) {}

  const Ref& operator=(const T& value) const {
    if (ptr) {
      *ptr = value;
    }
    return *this;
  }

  bool operator<(const Ref& rhs) const { return *ptr < *rhs.ptr; }
};
```

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


More information about the libcxx-commits mailing list