How to forward a mutable lambda - c++

Here's a watered down example of the code I'm try to compile:
#include <iostream>
#include <functional>
template <class F>
auto foo(F&& fun)
{
return [callback = std::forward<F>(fun)](auto&&... args) {
std::invoke(callback, std::forward<decltype(args)>(args)...);
};
}
int main()
{
std::string cur("running"), target("ok");
foo([s1 = cur, s2 = target](std::string const& arg) /*mutable*/ {
if (s1 == arg)
{
std::cout << s1 << std::endl;
}
})("not ok");
return 0;
}
put simply I have a function foo that accepts callables, and is supposed to build a new callable from them. For the sake of the example, above I'm just invoking the fun argument but in the real case there are some decorations done to the callable and the result is placed into a data structure that invokes such "actions" under some conditions.
This example compiles and works just fine. The problem manifests when trying to pass mutable lambdas to foo. When I uncomment the mutable keyword above, I get this compilation error:
main.cpp: In instantiation of 'foo<main()::<lambda(const string&)> >(main()::<lambda(const string&)>&&)::<lambda(auto:1&& ...)> [with auto:1 = {const char (&)[7]}]':
main.cpp:21:7: required from here
main.cpp:8:20: error: no matching function for call to 'invoke(const main()::<lambda(const string&)>&, const char [7])'
8 | std::invoke(callback, std::forward<decltype(args)>(args)...);
| ~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from main.cpp:2:
/usr/local/include/c++/11.2.0/functional:94:5: note: candidate: 'template<class _Callable, class ... _Args> std::invoke_result_t<_Callable, _Args ...> std::invoke(_Callable&&, _Args&& ...)'
94 | invoke(_Callable&& __fn, _Args&&... __args)
| ^~~~~~
/usr/local/include/c++/11.2.0/functional:94:5: note: template argument deduction/substitution failed:
In file included from /usr/local/include/c++/11.2.0/bits/move.h:57,
from /usr/local/include/c++/11.2.0/bits/nested_exception.h:40,
from /usr/local/include/c++/11.2.0/exception:148,
from /usr/local/include/c++/11.2.0/ios:39,
from /usr/local/include/c++/11.2.0/ostream:38,
from /usr/local/include/c++/11.2.0/iostream:39,
from main.cpp:1:
/usr/local/include/c++/11.2.0/type_traits: In substitution of 'template<class _Fn, class ... _Args> using invoke_result_t = typename std::invoke_result::type [with _Fn = const main()::<lambda(const string&)>&; _Args = {const char (&)[7]}]':
/usr/local/include/c++/11.2.0/functional:94:5: required by substitution of 'template<class _Callable, class ... _Args> std::invoke_result_t<_Callable, _Args ...> std::invoke(_Callable&&, _Args&& ...) [with _Callable = const main()::<lambda(const string&)>&; _Args = {const char (&)[7]}]'
main.cpp:8:20: required from 'foo<main()::<lambda(const string&)> >(main()::<lambda(const string&)>&&)::<lambda(auto:1&& ...)> [with auto:1 = {const char (&)[7]}]'
main.cpp:21:7: required from here
/usr/local/include/c++/11.2.0/type_traits:2933:11: error: no type named 'type' in 'struct std::invoke_result<const main()::<lambda(const string&)>&, const char (&)[7]>'
2933 | using invoke_result_t = typename invoke_result<_Fn, _Args...>::type;
| ^~~~~~~~~~~~~~~
Any idea why is that? Can my foo accept mutable lambdas as well?

Just add mutable to the lambda inside the foo:
template <class F>
auto foo(F&& fun)
{
return [callback = std::forward<F>(fun)](auto&&... args) mutable {
//^^^
std::invoke(callback, std::forward<decltype(args)>(args)...);
};
}

Related

c++ std::bind universal reference can't compile

#include <functional>
#include <iostream>
#include <type_traits>
using cb_t = std::function<void ()>;
template<typename CB_T, std::enable_if_t<std::is_constructible<cb_t, CB_T>::value, bool> = true>
void
on_my_write(int a, int b, CB_T&& cb) {
std::cout << "on_my_write:" << a << ", " << b << std::endl;
}
template<typename CB_T, std::enable_if_t<std::is_constructible<cb_t, CB_T>::value, bool> = true>
void foo(CB_T&& cb) {
auto b = std::bind(&on_my_write<CB_T>, std::placeholders::_1, std::placeholders::_2, std::forward<CB_T>(cb));
b(1, 2);
}
int main() {
foo([]{});
return 0;
}
compile this with command line
g++ ./try1.cpp -std=c++17
gave me:
./try1.cpp: In instantiation of ‘void foo(CB_T&&) [with CB_T = main()::<lambda()>; typename >std::enable_if<std::is_constructible<std::function<void()>, CB_T>::value, bool>::type <anonymous> = 1]’:
./try1.cpp:39:13: required from here
./try1.cpp:34:6: error: no match for call to ‘(std::_Bind<void (*(std::_Placeholder<1>, std::_Placeholder<2>, main()::<lambda()>))(int, int, main()::<lambda()>&&)>) (int, int)’
b(1, 2);
~^~~~~~
In file included from ./try1.cpp:19:0:
/usr/include/c++/7/functional:547:2: note: candidate: template<class ... _Args, class _Result> _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...) [with _Args = {_Args ...}; _Result = _Result; _Functor = void (*)(int, int, main()::<lambda()>&&); _Bound_args = {std::_Placeholder<1>, std::_Placeholder<2>, main()::<lambda()>}]
operator()(_Args&&... __args)
^~~~~~~~
/usr/include/c++/7/functional:547:2: note: template argument deduction/substitution failed:
/usr/include/c++/7/functional:558:2: note: candidate: template<class ... _Args, class _Result> _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...) const [with _Args = {_Args ...}; _Result = _Result; _Functor = void (*)(int, int, main()::<lambda()>&&); _Bound_args = {std::_Placeholder<1>, std::_Placeholder<2>, main()::<lambda()>}]
operator()(_Args&&... __args) const
^~~~~~~~
/usr/include/c++/7/functional:558:2: note: template argument deduction/substitution failed:
/usr/include/c++/7/functional:576:2: note: candidate: template<class ... _Args, class _Result> _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...) volatile [with _Args = {_Args ...}; _Result = _Result; _Functor = void (*)(int, int, main()::<lambda()>&&); _Bound_args = {std::_Placeholder<1>, std::_Placeholder<2>, main()::<lambda()>}]
operator()(_Args&&... __args) volatile
^~~~~~~~
/usr/include/c++/7/functional:576:2: note: template argument deduction/substitution failed:
/usr/include/c++/7/functional:588:2: note: candidate: template<class ... _Args, class _Result> _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...) const volatile [with _Args = {_Args ...}; _Result = _Result; _Functor = void (*)(int, int, main()::<lambda()>&&); _Bound_args = {std::_Placeholder<1>, std::_Placeholder<2>, main()::<lambda()>}]
operator()(_Args&&... __args) const volatile
^~~~~~~~
/usr/include/c++/7/functional:588:2: note: template argument deduction/substitution failed:
But if I change on_my_write(int a, int b, CB_T&& cb) to on_my_write(int a, int b, const CB_T& cb), then it will compile and run successfully.
I really don't understand why?
Could anybody explain this to me? thanks a lot!
I've tried several hours and can't figure it out.
Yes, this is slightly tricky. std::bind is of course not magical, it has to store the bound parameters somehow and it stores them as values by default, unless requested with std::ref argument.
Meaning that in the callstd::bind(...,std::forward<CB_T>(cb)), the cb is used to construct the bound member variable properly using the perfect forwarding.
But, the calling is not done with perfect forwarding sadly, the argument that bind will pass to on_my_write is always an l-value. It is not impossible to create std::bind version that would forward it and I do not know exactly why is it this way, but a good reason might be that such forwarding would make calling the bound functor multiple times dangerous.
So, since std::bind always passes the argument as l-value, you have a couple of options:
Remove perfect forwarding and use on_my_write(int a, int b, const CB_T& cb) as you did.
Remove perfect forwarding and move anyway, use on_my_write(int a, int b, CB_T& cb)
and use std::move(cb) inside to consume it. Be careful, this is exactly the case in which the new functor should be called just once.
Keep perfect forwarding but do not use it for this call which can be achieved by manually adding a reference:
std::bind(&on_my_write<CB_T&>, std::placeholders::_1, std::placeholders::_2,
std::forward<CB_T>(cb));
This will work thanks to reference collapsing rules and on_my_write(int a, int b, CB_T& cb) will be called always. You can still use 2. and move anyway.
Choose me Forget std::bind, use lambda:
template<typename CB_T, std::enable_if_t<std::is_constructible<cb_t, CB_T>::value,
bool> = true>
void foo(CB_T&& cb) {
auto b = [&cb](auto a,auto b){return on_my_write(a,b,std::forward<CB_T>(cb));};
b(1, 2);
}
This will forward cb properly, an extra advantage of this solution is that you do not have to deduce on_my_write manually.

Forwarding to std::async

This is my (simplified) code where I'm trying to call async forwarding arguments:
template<typename Ret, typename ... Args>
class CallbackAsyncTask {
public:
CallbackAsyncTask() {
}
virtual ~CallbackAsyncTask() = default;
void execute( Args&& ... args ) {
execute(&CallbackAsyncTask<Ret, Args...>::onBackground, this, std::forward<Args>(args)...);
}
protected:
virtual Ret onBackground( Args& ... args ) = 0;
template<typename Fn, typename ... Argss>
void execute( Fn&& fn, Argss&& ... args ) noexcept(false) {
std::async(std::launch::async, std::forward<Fn>(fn), std::forward<Argss>(args)...);
}
};
class Child: public CallbackAsyncTask<int, int> {
public:
virtual int onBackground( int& i ) {
return i;
}
};
int main() {
Child c;
c.execute(15);
return 0;
}
I get this error:
../main.cpp: In instantiation of ‘void CallbackAsyncTask<Ret, Args>::execute(Fn&&, Argss&& ...) [with Fn = int (CallbackAsyncTask<int, int>::*)(int&); Argss = {CallbackAsyncTask<int, int>* const, int}; Ret = int; Args = {int}]’:
../main.cpp:27:98: required from ‘void CallbackAsyncTask<Ret, Args>::execute(Args&& ...) [with Ret = int; Args = {int}]’
../main.cpp:46:17: required from here
../main.cpp:33:90: error: no matching function for call to ‘async(std::launch, int (CallbackAsyncTask<int, int>::*)(int&), CallbackAsyncTask<int, int>* const, int)’
std::async(std::launch::async, std::forward<Fn>(fn), std::forward<Argss>(args)...);
^
../main.cpp:33:90: note: candidates are:
In file included from ../main.cpp:13:0:
/usr/include/c++/4.8.2/future:1532:5: note: template<class _Fn, class ... _Args> std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(std::launch, _Fn&&, _Args&& ...)
async(launch __policy, _Fn&& __fn, _Args&&... __args)
^
/usr/include/c++/4.8.2/future:1532:5: note: template argument deduction/substitution failed:
/usr/include/c++/4.8.2/future: In substitution of ‘template<class _Fn, class ... _Args> std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(std::launch, _Fn&&, _Args&& ...) [with _Fn = int (CallbackAsyncTask<int, int>::*)(int&); _Args = {CallbackAsyncTask<int, int>* const, int}]’:
../main.cpp:33:90: required from ‘void CallbackAsyncTask<Ret, Args>::execute(Fn&&, Argss&& ...) [with Fn = int (CallbackAsyncTask<int, int>::*)(int&); Argss = {CallbackAsyncTask<int, int>* const, int}; Ret = int; Args = {int}]’
../main.cpp:27:98: required from ‘void CallbackAsyncTask<Ret, Args>::execute(Args&& ...) [with Ret = int; Args = {int}]’
../main.cpp:46:17: required from here
/usr/include/c++/4.8.2/future:1532:5: error: no type named ‘type’ in ‘class std::result_of<int (CallbackAsyncTask<int, int>::*(CallbackAsyncTask<int, int>*, int))(int&)>’
../main.cpp: In instantiation of ‘void CallbackAsyncTask<Ret, Args>::execute(Fn&&, Argss&& ...) [with Fn = int (CallbackAsyncTask<int, int>::*)(int&); Argss = {CallbackAsyncTask<int, int>* const, int}; Ret = int; Args = {int}]’:
../main.cpp:27:98: required from ‘void CallbackAsyncTask<Ret, Args>::execute(Args&& ...) [with Ret = int; Args = {int}]’
../main.cpp:46:17: required from here
/usr/include/c++/4.8.2/future:1552:5: note: template<class _Fn, class ... _Args> std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(_Fn&&, _Args&& ...)
async(_Fn&& __fn, _Args&&... __args)
^
/usr/include/c++/4.8.2/future:1552:5: note: template argument deduction/substitution failed:
/usr/include/c++/4.8.2/future: In substitution of ‘template<class _Fn, class ... _Args> std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(_Fn&&, _Args&& ...) [with _Fn = std::launch; _Args = {int (CallbackAsyncTask<int, int>::*)(int&), CallbackAsyncTask<int, int>* const, int}]’:
../main.cpp:33:90: required from ‘void CallbackAsyncTask<Ret, Args>::execute(Fn&&, Argss&& ...) [with Fn = int (CallbackAsyncTask<int, int>::*)(int&); Argss = {CallbackAsyncTask<int, int>* const, int}; Ret = int; Args = {int}]’
../main.cpp:27:98: required from ‘void CallbackAsyncTask<Ret, Args>::execute(Args&& ...) [with Ret = int; Args = {int}]’
../main.cpp:46:17: required from here
/usr/include/c++/4.8.2/future:1552:5: error: no type named ‘type’ in ‘class std::result_of<std::launch(int (CallbackAsyncTask<int, int>::*)(int&), CallbackAsyncTask<int, int>*, int)>’
What I am missing? Compiler Gcc 4.8.3
The root cause is these two lines
virtual Ret onBackground( Args& ... args ) = 0;
virtual int onBackground( int& i )
When launching the task, the arguments are converted either directly or as if by the std::thread constructor. That one does decay_copy on the arguments when invoking the callable, so a non-const lvalue reference cannot bind to the argument.
Change the way onBackground accepts arguments. For instance, a const lvalue refernce works. See live.

Using templates properly to pass functions to a threadpool

I'm attempting to make a threadpool that takes any kind of function, and returns a future for any return value/exceptions that function may have. I'm doing this largely as an exercise to learn modern threading and some template programming. I tried basing my syntax loosely off how MSVC does std::function and futures.
Here's a minimum snippet of where my problem is:
#include <functional>
#include <future>
#include <utility>
#include <queue>
#include <memory>
using Job = std::function<void()>;
std::queue<std::unique_ptr<Job>> queue;
template<typename FuncType, typename... Args>
auto add(FuncType&& func, Args&&... args) ->std::future<decltype(func)(decltype(args)...)> {
auto task = std::packaged_task<decltype(func)(decltype(args)...)>(std::bind (std::forward<FuncType>(func), std::forward<Args>(args)...));
auto future = task.get_future();
queue.push(std::make_unique<Job>([task]() { task(); }));
return future;
}
void voidFunc(){};
int main()
{
add(voidFunc);
}
This fails to compile with the errors:
/usr/include/c++/4.9/future: In instantiation of 'class std::future<void (&())()>':
28:17: required from here
/usr/include/c++/4.9/future:697:7: error: function returning a function
get()
^
In instantiation of 'add(FuncType&&, Args&& ...)::<lambda()> [with FuncType = void (&)(); Args = {}]':
19:37: required from 'struct add(FuncType&&, Args&& ...) [with FuncType = void (&)(); Args = {}; decltype (func) = void (&)()]::<lambda()>'
19:56: required from 'std::future<decltype (func)(decltype (args)...)> add(FuncType&&, Args&& ...) [with FuncType = void (&)(); Args = {}; decltype (func) = void (&)()]'
28:17: required from here
19:52: error: passing 'const std::packaged_task<void (&())()>' as 'this' argument of 'void std::packaged_task<_Res(_ArgTypes ...)>::operator()(_ArgTypes ...) [with _Res = void (&)(); _ArgTypes = {}]' discards qualifiers [-fpermissive]
In instantiation of 'std::future<decltype (func)(decltype (args)...)> add(FuncType&&, Args&& ...) [with FuncType = void (&)(); Args = {}; decltype (func) = void (&)()]':
28:17: required from here
19:36: error: use of deleted function 'std::packaged_task<_Res(_ArgTypes ...)>::packaged_task(const std::packaged_task<_Res(_ArgTypes ...)>&) [with _Res = void (&)(); _ArgTypes = {}]'
In file included from 5:0:
/usr/include/c++/4.9/future:1413:7: note: declared here
packaged_task(const packaged_task&) = delete;
^
21:10: error: could not convert 'future' from 'std::future<void (&)()>' to 'std::future<void (&())()>'
In file included from 5:0:
/usr/include/c++/4.9/future: In instantiation of 'static std::__future_base::_Task_setter<_Res_ptr> std::__future_base::_S_task_setter(_Res_ptr&, _BoundFn&&) [with _Res_ptr = std::unique_ptr<std::__future_base::_Result<void (&)()>, std::__future_base::_Result_base::_Deleter>; _BoundFn = std::_Bind_simple<std::reference_wrapper<std::_Bind<void (*())()> >()>; typename _Res_ptr::element_type::result_type = void (&)()]':
/usr/include/c++/4.9/future:1318:70: required from 'void std::__future_base::_Task_state<_Fn, _Alloc, _Res(_Args ...)>::_M_run(_Args ...) [with _Fn = std::_Bind<void (*())()>; _Alloc = std::allocator<int>; _Res = void (&)(); _Args = {}]'
29:1: required from here
/usr/include/c++/4.9/future:539:57: error: could not convert 'std::ref(_Tp&) [with _Tp = std::_Bind_simple<std::reference_wrapper<std::_Bind<void (*())()> >()>]()' from 'std::reference_wrapper<std::_Bind_simple<std::reference_wrapper<std::_Bind<void (*())()> >()> >' to 'std::function<void (&())()>'
return _Task_setter<_Res_ptr>{ __ptr, std::ref(__call) };
^
In file included from /usr/include/c++/4.9/memory:81:0,
from /usr/include/c++/4.9/thread:40,
from /usr/include/c++/4.9/future:40,
from 5:
/usr/include/c++/4.9/bits/unique_ptr.h:764:5: error: 'typename std::_MakeUniq<_Tp>::__single_object std::make_unique(_Args&& ...) [with _Tp = std::function<void()>; _Args = {add(FuncType&&, Args&& ...) [with FuncType = void (&)(); Args = {}; decltype (func) = void (&)()]::<lambda()>}; typename std::_MakeUniq<_Tp>::__single_object = std::unique_ptr<std::function<void()> >]', declared using local type 'add(FuncType&&, Args&& ...) [with FuncType = void (&)(); Args = {}; decltype (func) = void (&)()]::<lambda()>', is used but never defined [-fpermissive]
make_unique(_Args&&... __args)
^
In function 'std::future<decltype (func)(decltype (args)...)> add(FuncType&&, Args&& ...) [with FuncType = void (&)(); Args = {}; decltype (func) = void (&)()]':
22:2: warning: control reaches end of non-void function [-Wreturn-type]
I think I have two problems here: I don't know how to properly use decltype to get the right function signature (I've also looked into invoke_result, but I wasn't having any luck there either), and I think I'm probably also not passing the packaged task to the queue properly.
How do I get the right function signature for the future and packaged task, and how do I properly pass the packaged task to a std::function on a queue (that will later be grabbed by another thread)?
Two problems:
1) The signature of packaged task should be
std::packaged_task<std::invoke_result_t<Func&&,Args&&...>(Args&&...)>. This uses invoke_result_t to compute the return type, but also passes the argument types to the packaged task.
2) Bigger problem: std::function requires that the function be copy constructable, which std::packaged_task is not. You'll have to create your own queue to hold the packaged tasks. I've implemented it before using a base class Task with a templated derived class to hold the packaged task.

using std::bind with std::reference_wrapper::get

I'm trying to use std::bind to call std::reference_wrapper::get but I can't get it to compile. I'm sure I'm overlooking something obvious but the compiler errors are not helping me out. This code is contrived and doesn't represent my actual use case:
#include <functional>
#include <iostream>
struct A
{
void p() {std::cout << this << '\n';};
};
using ARef = std::reference_wrapper< A >;
int main()
{
A a;
a.p();
auto p = std::bind (&A::p, std::placeholders::_1);
p (a); // ok
ARef ar (a);
p (ar.get()); // ok
auto get = std::bind (&ARef::get, std::placeholders::_1);
p (get (ar)); // error
}
Edit: This compiles fine with clang.
gcc 6.3.0 output: http://coliru.stacked-crooked.com/a/00bffc7549193cb8
main.cpp: In function 'int main()':
main.cpp:21:19: error: no match for call to '(std::_Bind<std::_Mem_fn<A& (std::reference_wrapper<A>::*)() const noexcept>(std::_Placeholder<1>)>) (ARef&)'
p (get (ar)); // error
^
In file included from main.cpp:1:0:
/usr/local/include/c++/6.3.0/functional:989:2: note: candidate: template<class ... _Args, class _Result> _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...) [with _Args = {_Args ...}; _Result = _Result; _Functor = std::_Mem_fn<A& (std::reference_wrapper<A>::*)() const noexcept>; _Bound_args = {std::_Placeholder<1>}]
operator()(_Args&&... __args)
^~~~~~~~
/usr/local/include/c++/6.3.0/functional:989:2: note: template argument deduction/substitution failed:
/usr/local/include/c++/6.3.0/functional:985:39: error: no match for call to '(std::_Mem_fn<A& (std::reference_wrapper<A>::*)() const noexcept>) (std::reference_wrapper<A>&)'
= decltype( std::declval<_Functor&>()(
~~~~~~~~~~~~~~~~~~~~~~~~~^
_Mu<_Bound_args>()( std::declval<_Bound_args&>(),
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
std::declval<tuple<_Args...>&>() )... ) )>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/local/include/c++/6.3.0/functional:600:2: note: candidate: template<class ... _Args> decltype (std::__invoke(((const std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>*)this)->std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::_M_pmf, (forward<_Args>)(std::_Mem_fn_base::operator()::__args)...)) std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::operator()(_Args&& ...) const [with _Args = {_Args ...}; _MemFunPtr = A& (std::reference_wrapper<A>::*)() const noexcept; bool __is_mem_fn = true]
operator()(_Args&&... __args) const
^~~~~~~~
/usr/local/include/c++/6.3.0/functional:600:2: note: template argument deduction/substitution failed:
/usr/local/include/c++/6.3.0/functional: In substitution of 'template<class ... _Args> decltype (std::__invoke(((const std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>*)this)->std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::_M_pmf, (forward<_Args>)(std::_Mem_fn_base::operator()::__args)...)) std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::operator()(_Args&& ...) const [with _Args = {std::reference_wrapper<A>&}]':
/usr/local/include/c++/6.3.0/functional:985:39: required from here
/usr/local/include/c++/6.3.0/functional:603:27: error: no matching function for call to '__invoke(A& (std::reference_wrapper<A>::* const&)() const noexcept, std::reference_wrapper<A>&)'
-> decltype(std::__invoke(_M_pmf, std::forward<_Args>(__args)...))
~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/local/include/c++/6.3.0/functional:245:5: note: candidate: template<class _Callable, class ... _Args> typename std::result_of<_Callable&&(_Args&& ...)>::type std::__invoke(_Callable&&, _Args&& ...)
__invoke(_Callable&& __fn, _Args&&... __args)
^~~~~~~~
/usr/local/include/c++/6.3.0/functional:245:5: note: template argument deduction/substitution failed:
/usr/local/include/c++/6.3.0/functional: In substitution of 'template<class _Callable, class ... _Args> typename std::result_of<_Callable&&(_Args&& ...)>::type std::__invoke(_Callable&&, _Args&& ...) [with _Callable = A& (std::reference_wrapper<A>::* const&)() const noexcept; _Args = {std::reference_wrapper<A>&}]':
/usr/local/include/c++/6.3.0/functional:603:27: required by substitution of 'template<class ... _Args> decltype (std::__invoke(((const std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>*)this)->std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::_M_pmf, (forward<_Args>)(std::_Mem_fn_base::operator()::__args)...)) std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::operator()(_Args&& ...) const [with _Args = {std::reference_wrapper<A>&}]'
/usr/local/include/c++/6.3.0/functional:985:39: required from here
/usr/local/include/c++/6.3.0/functional:245:5: error: no type named 'type' in 'class std::result_of<A& (std::reference_wrapper<A>::* const&(std::reference_wrapper<A>&))() const noexcept>'
/usr/local/include/c++/6.3.0/functional:1003:2: note: candidate: template<class ... _Args, class _Result> _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...) const [with _Args = {_Args ...}; _Result = _Result; _Functor = std::_Mem_fn<A& (std::reference_wrapper<A>::*)() const noexcept>; _Bound_args = {std::_Placeholder<1>}]
operator()(_Args&&... __args) const
^~~~~~~~
/usr/local/include/c++/6.3.0/functional:1003:2: note: template argument deduction/substitution failed:
/usr/local/include/c++/6.3.0/functional:999:53: error: no match for call to '(const std::_Mem_fn<A& (std::reference_wrapper<A>::*)() const noexcept>) (std::reference_wrapper<A>&)'
= decltype( std::declval<typename enable_if<(sizeof...(_Args) >= 0),
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
typename add_const<_Functor>::type&>::type>()(
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~
/usr/local/include/c++/6.3.0/functional:600:2: note: candidate: template<class ... _Args> decltype (std::__invoke(((const std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>*)this)->std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::_M_pmf, (forward<_Args>)(std::_Mem_fn_base::operator()::__args)...)) std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::operator()(_Args&& ...) const [with _Args = {_Args ...}; _MemFunPtr = A& (std::reference_wrapper<A>::*)() const noexcept; bool __is_mem_fn = true]
operator()(_Args&&... __args) const
^~~~~~~~
/usr/local/include/c++/6.3.0/functional:600:2: note: template argument deduction/substitution failed:
/usr/local/include/c++/6.3.0/functional: In substitution of 'template<class ... _Args> decltype (std::__invoke(((const std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>*)this)->std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::_M_pmf, (forward<_Args>)(std::_Mem_fn_base::operator()::__args)...)) std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::operator()(_Args&& ...) const [with _Args = {std::reference_wrapper<A>&}]':
/usr/local/include/c++/6.3.0/functional:999:53: required from here
/usr/local/include/c++/6.3.0/functional:603:27: error: no matching function for call to '__invoke(A& (std::reference_wrapper<A>::* const&)() const noexcept, std::reference_wrapper<A>&)'
-> decltype(std::__invoke(_M_pmf, std::forward<_Args>(__args)...))
~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/local/include/c++/6.3.0/functional:245:5: note: candidate: template<class _Callable, class ... _Args> typename std::result_of<_Callable&&(_Args&& ...)>::type std::__invoke(_Callable&&, _Args&& ...)
__invoke(_Callable&& __fn, _Args&&... __args)
^~~~~~~~
/usr/local/include/c++/6.3.0/functional:245:5: note: template argument deduction/substitution failed:
/usr/local/include/c++/6.3.0/functional: In substitution of 'template<class _Callable, class ... _Args> typename std::result_of<_Callable&&(_Args&& ...)>::type std::__invoke(_Callable&&, _Args&& ...) [with _Callable = A& (std::reference_wrapper<A>::* const&)() const noexcept; _Args = {std::reference_wrapper<A>&}]':
/usr/local/include/c++/6.3.0/functional:603:27: required by substitution of 'template<class ... _Args> decltype (std::__invoke(((const std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>*)this)->std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::_M_pmf, (forward<_Args>)(std::_Mem_fn_base::operator()::__args)...)) std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::operator()(_Args&& ...) const [with _Args = {std::reference_wrapper<A>&}]'
/usr/local/include/c++/6.3.0/functional:999:53: required from here
/usr/local/include/c++/6.3.0/functional:245:5: error: no type named 'type' in 'class std::result_of<A& (std::reference_wrapper<A>::* const&(std::reference_wrapper<A>&))() const noexcept>'
/usr/local/include/c++/6.3.0/functional:1017:2: note: candidate: template<class ... _Args, class _Result> _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...) volatile [with _Args = {_Args ...}; _Result = _Result; _Functor = std::_Mem_fn<A& (std::reference_wrapper<A>::*)() const noexcept>; _Bound_args = {std::_Placeholder<1>}]
operator()(_Args&&... __args) volatile
^~~~~~~~
/usr/local/include/c++/6.3.0/functional:1017:2: note: template argument deduction/substitution failed:
/usr/local/include/c++/6.3.0/functional:1013:70: error: no match for call to '(volatile std::_Mem_fn<A& (std::reference_wrapper<A>::*)() const noexcept>) (std::reference_wrapper<A>&)'
= decltype( std::declval<typename enable_if<(sizeof...(_Args) >= 0),
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
typename add_volatile<_Functor>::type&>::type>()(
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~
/usr/local/include/c++/6.3.0/functional:600:2: note: candidate: template<class ... _Args> decltype (std::__invoke(((const std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>*)this)->std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::_M_pmf, (forward<_Args>)(std::_Mem_fn_base::operator()::__args)...)) std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::operator()(_Args&& ...) const [with _Args = {_Args ...}; _MemFunPtr = A& (std::reference_wrapper<A>::*)() const noexcept; bool __is_mem_fn = true]
operator()(_Args&&... __args) const
^~~~~~~~
/usr/local/include/c++/6.3.0/functional:600:2: note: template argument deduction/substitution failed:
/usr/local/include/c++/6.3.0/functional: In substitution of 'template<class ... _Args> decltype (std::__invoke(((const std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>*)this)->std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::_M_pmf, (forward<_Args>)(std::_Mem_fn_base::operator()::__args)...)) std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::operator()(_Args&& ...) const [with _Args = {std::reference_wrapper<A>&}]':
/usr/local/include/c++/6.3.0/functional:1013:70: required from here
/usr/local/include/c++/6.3.0/functional:603:27: error: no matching function for call to '__invoke(A& (std::reference_wrapper<A>::* const&)() const noexcept, std::reference_wrapper<A>&)'
-> decltype(std::__invoke(_M_pmf, std::forward<_Args>(__args)...))
~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/local/include/c++/6.3.0/functional:245:5: note: candidate: template<class _Callable, class ... _Args> typename std::result_of<_Callable&&(_Args&& ...)>::type std::__invoke(_Callable&&, _Args&& ...)
__invoke(_Callable&& __fn, _Args&&... __args)
^~~~~~~~
/usr/local/include/c++/6.3.0/functional:245:5: note: template argument deduction/substitution failed:
/usr/local/include/c++/6.3.0/functional: In substitution of 'template<class _Callable, class ... _Args> typename std::result_of<_Callable&&(_Args&& ...)>::type std::__invoke(_Callable&&, _Args&& ...) [with _Callable = A& (std::reference_wrapper<A>::* const&)() const noexcept; _Args = {std::reference_wrapper<A>&}]':
/usr/local/include/c++/6.3.0/functional:603:27: required by substitution of 'template<class ... _Args> decltype (std::__invoke(((const std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>*)this)->std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::_M_pmf, (forward<_Args>)(std::_Mem_fn_base::operator()::__args)...)) std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::operator()(_Args&& ...) const [with _Args = {std::reference_wrapper<A>&}]'
/usr/local/include/c++/6.3.0/functional:1013:70: required from here
/usr/local/include/c++/6.3.0/functional:245:5: error: no type named 'type' in 'class std::result_of<A& (std::reference_wrapper<A>::* const&(std::reference_wrapper<A>&))() const noexcept>'
/usr/local/include/c++/6.3.0/functional:1031:2: note: candidate: template<class ... _Args, class _Result> _Result std::_Bind<_Functor(_Bound_args ...)>::operator()(_Args&& ...) const volatile [with _Args = {_Args ...}; _Result = _Result; _Functor = std::_Mem_fn<A& (std::reference_wrapper<A>::*)() const noexcept>; _Bound_args = {std::_Placeholder<1>}]
operator()(_Args&&... __args) const volatile
^~~~~~~~
/usr/local/include/c++/6.3.0/functional:1031:2: note: template argument deduction/substitution failed:
/usr/local/include/c++/6.3.0/functional:1027:64: error: no match for call to '(const volatile std::_Mem_fn<A& (std::reference_wrapper<A>::*)() const noexcept>) (std::reference_wrapper<A>&)'
= decltype( std::declval<typename enable_if<(sizeof...(_Args) >= 0),
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
typename add_cv<_Functor>::type&>::type>()(
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~
/usr/local/include/c++/6.3.0/functional:600:2: note: candidate: template<class ... _Args> decltype (std::__invoke(((const std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>*)this)->std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::_M_pmf, (forward<_Args>)(std::_Mem_fn_base::operator()::__args)...)) std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::operator()(_Args&& ...) const [with _Args = {_Args ...}; _MemFunPtr = A& (std::reference_wrapper<A>::*)() const noexcept; bool __is_mem_fn = true]
operator()(_Args&&... __args) const
^~~~~~~~
/usr/local/include/c++/6.3.0/functional:600:2: note: template argument deduction/substitution failed:
/usr/local/include/c++/6.3.0/functional: In substitution of 'template<class ... _Args> decltype (std::__invoke(((const std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>*)this)->std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::_M_pmf, (forward<_Args>)(std::_Mem_fn_base::operator()::__args)...)) std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::operator()(_Args&& ...) const [with _Args = {std::reference_wrapper<A>&}]':
/usr/local/include/c++/6.3.0/functional:1027:64: required from here
/usr/local/include/c++/6.3.0/functional:603:27: error: no matching function for call to '__invoke(A& (std::reference_wrapper<A>::* const&)() const noexcept, std::reference_wrapper<A>&)'
-> decltype(std::__invoke(_M_pmf, std::forward<_Args>(__args)...))
~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/local/include/c++/6.3.0/functional:245:5: note: candidate: template<class _Callable, class ... _Args> typename std::result_of<_Callable&&(_Args&& ...)>::type std::__invoke(_Callable&&, _Args&& ...)
__invoke(_Callable&& __fn, _Args&&... __args)
^~~~~~~~
/usr/local/include/c++/6.3.0/functional:245:5: note: template argument deduction/substitution failed:
/usr/local/include/c++/6.3.0/functional: In substitution of 'template<class _Callable, class ... _Args> typename std::result_of<_Callable&&(_Args&& ...)>::type std::__invoke(_Callable&&, _Args&& ...) [with _Callable = A& (std::reference_wrapper<A>::* const&)() const noexcept; _Args = {std::reference_wrapper<A>&}]':
/usr/local/include/c++/6.3.0/functional:603:27: required by substitution of 'template<class ... _Args> decltype (std::__invoke(((const std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>*)this)->std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::_M_pmf, (forward<_Args>)(std::_Mem_fn_base::operator()::__args)...)) std::_Mem_fn_base<_MemFunPtr, __is_mem_fn>::operator()(_Args&& ...) const [with _Args = {std::reference_wrapper<A>&}]'
/usr/local/include/c++/6.3.0/functional:1027:64: required from here
/usr/local/include/c++/6.3.0/functional:245:5: error: no type named 'type' in 'class std::result_of<A& (std::reference_wrapper<A>::* const&(std::reference_wrapper<A>&))() const noexcept>'
It is illegal to take the address of standard library member functions, because implementations can add overloads and mutilate their signatures at will. Therefore, the standard library, and in particular the INVOKE protocol used by bind and friends, is designed around the assumption that it won't be passed a pointer to member of std::reference_wrapper. Invoking a pointer to member pm with a reference_wrapper r is equivalent to invoking pm with r.get(); i.e., the reference is unconditionally unwrapped.
See also LWG issue 2219, which added reference_wrapper handling to INVOKE.

Is it possible to capture a variable number of parameters in a lambda?

Consider the following set of examples.
The function takeOnlyVoidFunction takes a function with zero arguments and simply executes it.
The function takeVariableArguments takes a variable number of arguments and executes the function using the arguments.
The function captureVariableArgs attempts to convert the second function into a lambda form that is acceptable by the first function, but it does not compile.
How can I make the function captureVariableArgs compile and exhibit the correct behavior of converting a function with a variable number of arguments into a closure with no arguments?
#include <stdio.h>
#include <functional>
void takeOnlyVoidFunction(std::function<void()> task) {
task();
}
template<typename _Callable, typename... _Args>
void takeVariableArguments(_Callable&& __f, _Args&&... __args) {
__f(__args...);
}
// How can I make this function compile?
template<typename _Callable, typename... _Args>
void captureVariableArgs(_Callable&& __f, _Args&&... __args) {
takeOnlyVoidFunction([=]() { __f(__args...);});
}
void normalFunction(int a, int b) {
printf("I am a normal function which takes params (%d,%d)\n", a, b);
}
int main() {
int a = 7;
int b = 8;
takeVariableArguments(normalFunction, a, b);
takeOnlyVoidFunction([=](){ normalFunction(a,b);});
captureVariableArgs(normalFunction, a, b);
}
I'm running gcc 4.9.2. Here is the compiler error I see.
g++ -std=c++11 Test.cc -o Test
Test.cc: In instantiation of ‘captureVariableArgs(_Callable&&, _Args&& ...)::<lambda()> [with _Callable = void (&)(int, int); _Args = {int&, int&}]’:
Test.cc:16:38: required from ‘struct captureVariableArgs(_Callable&&, _Args&& ...) [with _Callable = void (&)(int, int); _Args = {int&, int&}]::<lambda()>’
Test.cc:16:50: required from ‘void captureVariableArgs(_Callable&&, _Args&& ...) [with _Callable = void (&)(int, int); _Args = {int&, int&}]’
Test.cc:28:45: required from here
Test.cc:16:34: error: variable ‘__f’ has function type
takeOnlyVoidFunction([=]() { __f(__args...);});
^
Test.cc:16:34: error: variable ‘__f’ has function type
Test.cc: In instantiation of ‘struct captureVariableArgs(_Callable&&, _Args&& ...) [with _Callable = void (&)(int, int); _Args = {int&, int&}]::<lambda()>’:
Test.cc:16:50: required from ‘void captureVariableArgs(_Callable&&, _Args&& ...) [with _Callable = void (&)(int, int); _Args = {int&, int&}]’
Test.cc:28:45: required from here
Test.cc:16:34: error: field ‘captureVariableArgs(_Callable&&, _Args&& ...) [with _Callable = void (&)(int, int); _Args = {int&, int&}]::<lambda()>::<__f capture>’ invalidly declared function type
In file included from Test.cc:2:0:
/usr/include/c++/4.9/functional:2418:7: error: ‘std::function<_Res(_ArgTypes ...)>::function(_Functor) [with _Functor = captureVariableArgs(_Callable&&, _Args&& ...) [with _Callable = void (&)(int, int); _Args = {int&, int&}]::<lambda()>; <template-parameter-2-2> = void; _Res = void; _ArgTypes = {}]’, declared using local type ‘captureVariableArgs(_Callable&&, _Args&& ...) [with _Callable = void (&)(int, int); _Args = {int&, int&}]::<lambda()>’, is used but never defined [-fpermissive]
function<_Res(_ArgTypes...)>::
^
Update: A more minimal example demonstrating this problem.
#include <stdio.h>
// How can I make this function compile?
template<typename _Callable>
void captureVariableArgs(_Callable&& __f) {
takeOnlyVoidFunction( [=]{ __f(); } );
}
void normalFunction() {
printf("I am a normal function\n");
}
int main(){
captureVariableArgs(normalFunction);
}
As another potential workaround for GCC, instead of using a lambda, you could use std::bind:
template <typename F, typename... Args>
auto captureVariable(F&& f, Args&&... args)
{
return std::bind(std::forward<F>(f), std::forward<Args>(args)...);
}
This works for me under GCC 4.9.3.
The code in the post compiles fine with the latest clang&MSVC compilers but all the gccs refuse to compile it. So it seems a bug in gcc. Nevertheless, I found a way to make gcc happy: just don't use an "universal reference" on the callable argument, like this:
template<typename _Callable, typename... _Args>
int captureVariableArgs(_Callable _f, _Args&&... _args) {
return takeOnlyVoidFunction([=]() { _f(_args...);});
}
I can't explain why gcc doesn't accept your version, though. I'm not familiar with gcc-style error reporting and can't extract the true cause from the error message. But I think the workaround is ok since I don't see any value in "universal reference" in this case. In fact, I don't see why you use it on the args either.