I would like to control threads
, so each new issued thread
will go through my code first.
This way, each new thread issued with runThread()
in the example below, will first call the function runInnerThread()
below (in which I do some kind of initializations) and then call the desired function.
I've tried putting something like this:
#include <iostream>
#include <thread>
template<typename _Callable, typename... _Args>
void runThreadInner(_Callable&& __f, _Args&&... __args) {
// My initializations...
__f(__args...);
// My finishing...
};
template<typename _Callable, typename... _Args>
bool runThread(_Callable&& __f, _Args&&... __args) {
std::thread t(std::bind(&runThreadInner,
std::forward<_Callable>(__f),
std::forward<_Args>(__args)...));
}
int main() {
runThread([]() {
std::cout << std::this_thread::get_id() << "Threading...\n";
});
return 0;
}
I get an error from the compiler which complains about deducing
runThreadInner()
templates
main.cpp: In instantiation of ‘bool runThread(_Callable&&, _Args&& ...) [with _Callable = main()::__lambda0; _Args = {}]’:
main.cpp:43:3: required from here
main.cpp:27:38: error: no matching function for call to ‘bind(<unresolved overloaded function type>, main()::__lambda0)’
std::forward<_Args>(__args)...));
^
main.cpp:27:38: note: candidates are:
In file included from /usr/include/c++/4.8/memory:79:0,
from main.cpp:2:
/usr/include/c++/4.8/functional:1655:5: note: template<class _Func, class ... _BoundArgs> typename std::_Bind_helper<std::__or_<std::is_integral<typename std::decay<_Tp>::type>, std::is_enum<typename std::decay<_Tp>::type> >::value, _Func, _BoundArgs ...>::type std::bind(_Func&&, _BoundArgs&& ...)
bind(_Func&& __f, _BoundArgs&&... __args)
^
/usr/include/c++/4.8/functional:1655:5: note: template argument deduction/substitution failed:
main.cpp:27:38: note: couldn't deduce template parameter ‘_Func’
std::forward<_Args>(__args)...));
^
In file included from /usr/include/c++/4.8/memory:79:0,
from main.cpp:2:
/usr/include/c++/4.8/functional:1682:5: note: template<class _Result, class _Func, class ... _BoundArgs> typename std::_Bindres_helper<_Result, _Func, _BoundArgs>::type std::bind(_Func&&, _BoundArgs&& ...)
bind(_Func&& __f, _BoundArgs&&... __args)
^
/usr/include/c++/4.8/functional:1682:5: note: template argument deduction/substitution failed:
main.cpp:27:38: note: couldn't deduce template parameter ‘_Result’
std::forward<_Args>(__args)...));
I tried explicitly defining the template, without any success:
template<typename _Callable, typename... _Args>
bool runThread(_Callable&& __f, _Args&&... __args) {
std::thread t(std::bind(&runThreadInner<_Callable, _Args>,
std::forward<_Callable>(__f),
std::forward<_Args>(__args)...));
}
Is it possible? Thanks.