std :: package_task 및 std :: thread를 사용하여 std :: async를 에뮬레이트 한 Antony Williams - C++ Concurrency in Action 예제 4.14를 사용하여 연주하고 있습니다.packaged_task가있는 템플릿이 컴파일되지 않았습니다
줄을 주석 처리 할 때이 코드가 컴파일되지 않고 왜 작동하도록하려면이 코드를 다시 작성해야합니까?
#include <iostream>
#include <future>
#include <thread>
#include <string>
void func_string(const std::string &x) {}
void func_int(int x) {}
template <typename F, typename A>
std::future<typename std::result_of<F(A&&)>::type> spawn_task(F &&f, A &&a) {
typedef typename std::result_of<F(A&&)>::type result_type;
std::packaged_task<result_type(A&&)> task(std::move(f));
std::future<result_type> res(task.get_future());
std::thread t(std::move(task), std::move(a));
t.detach();
return res;
}
int main() {
std::string str = "abc";
// auto res1 = spawn_task(func_string, str);
// res1.get();
auto res2 = spawn_task(func_int, 10);
res2.get();
return 0;
}
컴파일 오류 모든 std::packaged_task
의
[email protected] /tmp $ clang++ -std=c++11 -lpthread temp.cpp && ./a.out
In file included from temp.cpp:2:
In file included from /usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../include/c++/4.8.2/future:38:
/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../include/c++/4.8.2/functional:1697:56: error: no type
named 'type' in 'std::result_of<std::packaged_task<void (std::basic_string<char> &)> (std::basic_string<char>)>'
typedef typename result_of<_Callable(_Args...)>::type result_type;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~
/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../include/c++/4.8.2/thread:135:41: note: in instantiation
of template class 'std::_Bind_simple<std::packaged_task<void (std::basic_string<char> &)>
(std::basic_string<char>)>' requested here
_M_start_thread(_M_make_routine(std::__bind_simple(
^
temp.cpp:15:15: note: in instantiation of function template specialization 'std::thread::thread<std::packaged_task<void
(std::basic_string<char> &)>, std::basic_string<char> >' requested here
std::thread t(std::move(task), std::move(a));
^
temp.cpp:24:15: note: in instantiation of function template specialization 'spawn_task<void (&)(const
std::basic_string<char> &), std::basic_string<char> &>' requested here
auto res1 = spawn_task(func_string, str);
^
In file included from temp.cpp:2:
In file included from /usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../include/c++/4.8.2/future:38:
/usr/bin/../lib64/gcc/x86_64-unknown-linux-gnu/4.8.2/../../../../include/c++/4.8.2/functional:1726:50: error: no type
named 'type' in 'std::result_of<std::packaged_task<void (std::basic_string<char> &)> (std::basic_string<char>)>'
typename result_of<_Callable(_Args...)>::type
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~
2 errors generated.
컴파일 오류를 제공 할 수 있습니까? – Chnossos
@Chnossos가 추가되었습니다. – nnovzver
컴파일은'void func_string (std :: string && x)'와 같은 함수 시그니처의 변경과 함께 작동하고'std :: move (str)'을 사용합니다. 나는 일반적인 경우에 완벽하게 포워딩을 처리하는 방법을 여전히 잘 모르고있다 ... – galop1n