以下是我试图使其在中工作的片段
#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;
}
用clang++编译给了我
➜ /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.
我不知道这是否真的与捕获条款有关。如何使代码片段正常工作?
这首先不是std::forward
的用例;foo
的aFunction
不是通用/转发引用,因此std::forward
不适用。
您只想无条件地移动r值引用,将其传递给bar
;将代码更改为:
bar(std::move(aFunction));
足以使之发挥作用。