gpt4 book ai didi

c++ - 通过完美转发将可变参数模板参数作为对 std::thread 的引用传递

转载 作者:行者123 更新时间:2023-11-28 05:03:21 24 4
gpt4 key购买 nike

<分区>

考虑这个简单的可变参数模板函数,它生成一个线程并将参数转发给线程函数。为什么我在这里的线程构造函数上会出现模板替换失败?

std::thread t;

void test3(int& a)
{
a = 10;
}

template<class ...Args>
void test(Args&&... args)
{
t = std::thread(test3, std::forward<Args>(args)...);
}

int main()
{
auto timer = 2s;

int a = 1;
test(a);
std::this_thread::sleep_for(timer);
std::cout << a << std::endl;
t.join();
}

编译器输出:

template argument deduction/substitution failed:
/opt/wandbox/gcc-head/include/c++/8.0.0/bits/invoke.h: In substitution of
'template<class _Callable, class ... _Args> constexpr typename
std::__invoke_result<_Functor, _ArgTypes>::type std::__invoke(_Callable&&,
_Args&& ...) [with _Callable = void (*)(int&); _Args = {int}]':
/opt/wandbox/gcc-head/include/c++/8.0.0/thread:233:29: required by
substitution of 'template<long unsigned int ..._Ind> decltype
(std::__invoke(_S_declval<_Ind>()...)) std::thread::_Invoker<std::tuple<void
(*)(int&), int> >::_M_invoke<_Ind ...>(std::_Index_tuple<_Ind1 ...>) [with
long unsigned int ..._Ind = {0, 1}]'
/opt/wandbox/gcc-head/include/c++/8.0.0/thread:240:2: required from
'struct std::thread::_Invoker<std::tuple<void (*)(int&), int> >'
/opt/wandbox/gcc-head/include/c++/8.0.0/thread:127:22: required from
'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)
(int&); _Args = {int&}]'
prog.cc:23:14: required from 'void test(Args&& ...) [with Args = {int&}]'
prog.cc:43:11: required from here
/opt/wandbox/gcc-head/include/c++/8.0.0/bits/invoke.h:89:5: error: no type
named 'type' in 'struct std::__invoke_result<void (*)(int&), int>'

当我用这样的 std::ref 包装参数的转发时:

std::thread(test3, std::ref(std::forward<Args>(args)...));

它有效。论点不是应该首先完美转发吗?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com