如何使用默认参数将函数传递给std :: thread?

12

我使用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 << "A\n";
}

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
任何建议或解决方案?提前感谢!
1个回答

22
thread two (print_int);

在C++中,你不能这样做。默认参数只在调用时使用(例如当你自己调用print_int()时),它是一种语法快捷方式,但不适用于像std::thread这样通过参数传递相同函数的情况。问题在于,std::thread 得到一个指向具有一个参数的函数的指针,但没有传递与之对应的参数,所以它不知道如何调用该函数,也没有办法在给定函数指针的情况下查找函数的默认参数。

最简单的解决方法是使用lambda调用该函数,因为该调用可以使用默认参数:

thread two( []{ print_int(); } );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接