【发布时间】:2018-04-21 16:37:10
【问题描述】:
以下函数模板来自 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 传递给线程构造函数吗?
【问题讨论】:
-
11.3.6 似乎建议稍后添加默认参数仅适用于非模板函数。不知道反过来是否适用。 Stroustrup 的示例没有初始声明,而是将默认值放在定义中。
标签: c++ multithreading language-lawyer