I'd like to have a wrapper thread function, i.e. a function executed by a thread which does some extra stuff, and then calls the user function.
template<class F, class... Args> void wrapper(F&& user_function, Args&&... args) { // do some extra stuff user_function(args); // maybe I need to forward args // do some extra stuff } Ok, this could be a nice wrapper, so I need a manager that uses this wrapper function and allows the user to spawn his own threads:
class ThreadManager { public: template<class F, class... Args> std::thread newThread(F&& f, Args&&... args) { return std::thread(thread_wrapper<F,Args...>, std::forward<F>(f), std::forward<Args>(args)...); } }; this way the thread manager SHOULD spawn a thread that uses the wrapper function which, in turn, does its extra work and calls the user function.
But the compiler now says: Attempt to use a deleted function.
The error is in the thread header:
template <class _Fp, class ..._Args, size_t ..._Indices> inline _LIBCPP_INLINE_VISIBILITY void __thread_execute(tuple<_Fp, _Args...>& __t, __tuple_indices<_Indices...>) { __invoke(_VSTD::move(_VSTD::get<0>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...); } What am I missing/doing wrong?
[edit]
Using test:
void foo(int i) { std::cout << "foo: " << i << std::endl; } int main(int argc, const char *argv[]) { ThreadManager mgr; auto t = mgr.newThread(foo, 10); t.detach(); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); return 0; } I'm using Xcode 7.1 with LLVM compiler, but fails on FreeBSD clang 3.3 too.
The Xcode error is:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:337:5: error: attempt to use a deleted function __invoke(_VSTD::move(_VSTD::get<0>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...); ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:347:5: note: in instantiation of function template specialization 'std::__1::__thread_execute' requested here __thread_execute(*__p, _Index()); ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:359:42: note: in instantiation of function template specialization 'std::__1::__thread_proxy >' requested here int __ec = pthread_create(&__t_, 0, &__thread_proxy<_Gp>, __p.get());
thread_wrapper<F, Args...>will turn your perfect forwardingF&&andArgs&¶meters into actual rvalue reference parameters.