gpt4 book ai didi

c++ - 线程调用函数模板时的编译错误(对于默认参数)

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

以下函数模板来自 Stroustrup 的书(“CPL”,第 4 版):

template<typename Arg1, typename Arg2, typename Arg3>
void write(Arg1 a1, Arg2 a2 = {}, Arg3 a3 = {});

template<typename Arg1, typename Arg2, typename Arg3>
void write(Arg1 a1, Arg2 a2, Arg3 a3)
{
thread::id name = this_thread::get_id();

coutm.lock();

cout << "From thread " << name << " : "
<< a1 << ' ' << a2 << ' ' << a3
<< endl;

coutm.unlock();
}


我正在尝试执行以下操作 here :
1) 调用此函数仅传递 2 个参数。第三个参数应该默认。
2) 函数模板调用直接传递给线程(而不是通过 lambda)。

int main()
{
thread t (write<char, float>, 'a', 4.9);

t.join();
}


但是,我得到以下编译错误:

main.cpp: In function 'int main()':
main.cpp:22:42: error: no matching function for call to 'std::thread::thread(<unresolved overloaded function type>, char, double)'

thread t (write<char, float>, 'a', 4.9);
^
In file included from main.cpp:7:0:
/usr/local/include/c++/7.2.0/thread:118:7: note: candidate: template<class _Callable, class ... _Args> std::thread::thread(_Callable&&, _Args&& ...)

thread(_Callable&& __f, _Args&&... __args)
^~~~~~
/usr/local/include/c++/7.2.0/thread:118:7: note: template argument deduction/substitution failed:
main.cpp:22:42: note: couldn't deduce template parameter '_Callable'

thread t (write<char, float>, 'a', 4.9);
^
In file included from main.cpp:7:0:
/usr/local/include/c++/7.2.0/thread:113:5: note: candidate: std::thread::thread(std::thread&&)

thread(thread&& __t) noexcept
^~~~~~

/usr/local/include/c++/7.2.0/thread:113:5: note: candidate expects 1 argument, 3 provided
/usr/local/include/c++/7.2.0/thread:106:5: note: candidate: std::thread::thread()

thread() noexcept = default;
^~~~~~

/usr/local/include/c++/7.2.0/thread:106:5: note: candidate expects 0 arguments, 3 provided


对于默认参数,是否可以通过线程直接调用这样的函数模板?如果是这样怎么办?否则,必须将 lambda 传递给线程构造函数吗?

最佳答案

无法从默认(函数)参数推导出模板参数。您没有明确指定 Arg3,因此无法实例化 write。换句话说,您希望 a3 在线程对 write 的调用中是什么类型

关于c++ - 线程调用函数模板时的编译错误(对于默认参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49957946/

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