【发布时间】:2022-01-12 21:11:45
【问题描述】:
我怎样才能使它工作?
#include <iostream>
#include <thread>
using namespace std;
int main()
{
auto thr = []<typename PrintType>( PrintType &p )
{
cout << p << endl;
};
string str = "hello world";
jthread jt( thr, ref( str ) );
}
我什至不明白这里有什么问题。
这是 Windows 上的 clang 13 所说的:
In file included from test.cpp:2:
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\include\thread:55:9: error: no matching function for call to 'invoke'
_STD invoke(_STD move(_STD get<_Indices>(_Tup))...);
^~~~~~~~~~~
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\include\yvals_core.h:1385:20: note: expanded from macro '_STD'
#define _STD ::std::
^
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\include\thread:62:17: note: in instantiation of function template specialization 'std::thread::_Invoke<std::tuple<(lambda at test.cpp:8:13), std::reference_wrapper<std::basic_string<char>>>, 0ULL, 1ULL>' requested here
return &_Invoke<_Tuple, _Indices...>;
^
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\include\thread:302:19: note: in instantiation of function template specialization 'std::thread::_Start<(lambda at test.cpp:8:13) &, std::reference_wrapper<std::basic_string<char>>>' requested here
_Impl._Start(_STD forward<_Fn>(_Fx), _STD forward<_Args>(_Ax)...);
^
test.cpp:13:10: note: in instantiation of function template specialization 'std::jthread::jthread<(lambda at test.cpp:8:13) &, std::reference_wrapper<std::basic_string<char>>, 0>' requested here
jthread jt( thr, ref( str ) );
^
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\include\type_traits:1482:19: note: candidate template ignored: substitution failure [with _Callable = (lambda at test.cpp:8:13), _Ty1 = std::reference_wrapper<std::basic_string<char>>, _Types2 = <>]: no matching function for call to '_Call'
_CONSTEXPR17 auto invoke(_Callable&& _Obj, _Ty1&& _Arg1, _Types2&&... _Args2) noexcept(
^
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.30.30705\include\type_traits:1476:19: note: candidate function template not viable: requires single argument '_Obj', but 2 arguments were provided
_CONSTEXPR17 auto invoke(_Callable&& _Obj) noexcept(noexcept(static_cast<_Callable&&>(_Obj)()))
^
1 error generated.
【问题讨论】:
-
您可以在 lambda 中使用
auto并避免使用模板。[](const auto &t){ cout << t << endl; }; -
另外,我不鼓励您在不确保线程生命周期的情况下将某些内容作为引用传递给线程
-
让我们从您忘记包含
cout的标题开始。然后,你认为jthread会来自哪里 -
@BonitaMontero this 为我编译了一些小的修改。
-
@BonitaMontero 我不确定你的意思。您的问题似乎是“我怎样才能使它工作?”
标签: c++ variadic-templates c++20