简体   繁体   中英

Can I perfect forwarding an lambda function without knowing the capture?

Here's the snippet that I am trying to make it work

#include <functional>
#include <stdio.h>
#include <utility>

void
bar(std::function<void(int* a)>&& aFunction)
{}

void
foo(std::function<void(int* a)>&& aFunction)
{
  bar(std::forward(aFunction));
}

int
main()
{
  int b = 123;
  foo([b](int*) { printf("Calling \n"); });
  return 0;
}

Compiling with clang++ gives me

➜  /tmp clang++ main.cpp -g -o main
main.cpp:12:7: error: no matching function for call to 'forward'
  bar(std::forward(aFunction));
      ^~~~~~~~~~~~
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/10.2.0/../../../../include/c++/10.2.0/bits/move.h:76:5: note: candidate template ignored: couldn't infer template argument '_Tp'
    forward(typename std::remove_reference<_Tp>::type& __t) noexcept
    ^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/10.2.0/../../../../include/c++/10.2.0/bits/move.h:87:5: note: candidate template ignored: couldn't infer template argument '_Tp'
    forward(typename std::remove_reference<_Tp>::type&& __t) noexcept
    ^
1 error generated.

I don't know if this is related to the capture clause actually. How can I make the code snippet work?

This is not a use case for std::forward in the first place; foo 's aFunction is not a universal/forwarding reference , so std::forward doesn't apply.

You just want to unconditionally move the r-value reference to pass it along to bar ; changing the code to:

bar(std::move(aFunction));

is sufficient to make that work .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM