如何使用默认参数将函数传递给std:: thread
How can I pass a function using default parameter(s) to std:: thread?
所以我有gcc版本4.8.1,g++版本4.6.4,使用标志:-std=c++0x和-pthread.
我将问题简化为所示的代码,仍然得到原始错误。
下面的代码可以编译,但是当我取消对线程"two"的两行注释时,我得到了如下代码
所示的错误消息#include <iostream>
#include <thread>
using namespace std;
void print_int(int x=7);
void print_A(){
cout << "An";
}
int main(){
thread one (print_int,17);
//thread two (print_int);
thread three (print_A);
one.join();
//two.join();
three.join();
return 0;
}
void print_int(int x){
cout << x << 'n';
}
我试着解析错误信息,但我仍然不知道发生了什么…
In file included from /usr/include/c++/4.6/thread:39:0,
from def_params.cpp:2:
/usr/include/c++/4.6/functional: In member function ‘void std::_Bind_result<_Result, _Functor(_Bound_args ...)>::__call(std::tuple<_Args ...>&&, std::_Index_tuple<_Indexes ...>, typename std::_Bind_result<_Result, _Functor(_Bound_args ...)>::__enable_if_void<_Res>::type) [with _Res = void, _Args = {}, int ..._Indexes = {}, _Result = void, _Functor = void (*)(int), _Bound_args = {}, typename std::_Bind_result<_Result, _Functor(_Bound_args ...)>::__enable_if_void<_Res>::type = int]’:
/usr/include/c++/4.6/functional:1378:24: instantiated from ‘std::_Bind_result<_Result, _Functor(_Bound_args ...)>::result_type std::_Bind_result<_Result, _Functor(_Bound_args ...)>::operator()(_Args&& ...) [with _Args = {}, _Result = void, _Functor = void (*)(int), _Bound_args = {}, std::_Bind_result<_Result, _Functor(_Bound_args ...)>::result_type = void]’
/usr/include/c++/4.6/thread:117:13: instantiated from ‘void std::thread::_Impl<_Callable>::_M_run() [with _Callable = std::_Bind_result<void, void (*())(int)>]’
def_params.cpp:26:9: instantiated from here
/usr/include/c++/4.6/functional:1287:4: error: too few arguments to function
有什么建议或解决方案吗?提前感谢!
thread two (print_int);
你不能这样做,c++中的默认参数只在调用站点(例如当你自己调用print_int()
时)作为语法快捷方式使用,但当std::thread
调用作为参数传递给它的相同函数时不使用。问题是std::thread
得到一个指向单参数函数的指针,但没有传递一个参数与它一起,所以它不知道如何调用它,并且没有办法查找函数的默认参数给定一个指向函数的指针。
最简单的解决方案是使用lambda调用函数,因为该调用可以使用默认实参:
thread two( []{ print_int(); } );
相关文章:
- 在std::thread中,joinable()然后join()线程安全吗
- 分离一个静态常量 std::thread?
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 如何从 std::thread 返回值
- 将 std::thread by 值推送到列表中
- 转发变量参数列表以模拟 std::thread
- 对 'std::thread::_M_start_thread CMake 的未定义引用进行基准测试
- std::thread 增加 DLL 引用计数,从而防止卸载 DLL
- 如何防止 std::thread 在 QT 中冻结 GUI?
- 对带有唯一指针的 std::thread 使用类成员函数时出现编译错误
- 为什么参数在构造 std::thread 时移动两次
- std::thread::_Invoker 使用线程编程时出错
- 在线程 A 中创建一个 std::thread 对象,在线程 B 中连接
- 为什么编译器抱怨 std::thread 参数在转换为右值后必须是可调用的?
- ZeroMQ 在使用 std::thread 创建工作线程时崩溃
- 在没有复制构造函数的对象的成员函数中启动 std::thread
- CLang:在 std::thread 中运行函数会导致结构创建BAD_ACCESS
- 调用以CWinThread为基的类运算符()的std::thread失败
- 如何通过std::thread生成多个线程
- std::future::get()或std::future::wait()是std::thread::join()的替