无法使用参数调用线程函数

Calling threaded functions with arguments not possible

我知道这个问题看起来和已经回答过的问题很相似,但是因为给他们的答案对我不起作用,我不认为这个问题是他们的重复

我很清楚这个问题:我如何将 c++ 函数调用为具有 1 个或多个参数的线程已经回答了好几次——无论是在这里还是在各种教程中——在每种情况下答案很简单,就是这样做的方法:

(示例直接取自 this question

#include <string>
#include <iostream>
#include <thread>

using namespace std;

// The function we want to execute on the new thread.
void task1(string msg)
{
    cout << "task1 says: " << msg;
}

int main()
{
    // Constructs the new thread and runs it. Does not block execution.
    thread t1(task1, "Hello");

    // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
    t1.join();
}

但是我已经尝试复制粘贴此代码和更多(或多或少相同的)如何执行此操作的示例,但是,每次我编译时(通过 terminal g++ test.cpp -o test.app(.app必须添加,因为我在Mac(请注意,这种编译方式实际上对我有用,而且错误根本不是我不知道如何编译c++的结果程序))) 这样的程序我得到这个错误信息:

test.cpp:16:12: error: no matching constructor for initialization of 'std::__1::thread'
    thread t1(task1, "Hello");
           ^  ~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:389:9: note: candidate constructor template not viable: requires single argument '__f', but
      2 arguments were provided
thread::thread(_Fp __f)
        ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:297:5: note: candidate constructor not viable: requires 1 argument, but 2 were provided
    thread(const thread&);
    ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/thread:304:5: note: candidate constructor not viable: requires 0 arguments, but 2 were provided
    thread() _NOEXCEPT : __t_(0) {}

我的问题是,与所有积极地可以使用参数创建线程函数的人相比,我做错了什么,而且由于我没有发现遇到类似问题的人提出的任何问题,我不要认为这个问题是许多问题的重复 How do i call a threaded function with arguments

据我所知,使用线程不需要任何特定的编译器标志,并且由于我完全可以 运行 程序使用不带参数的线程函数,所以你不能声称我的计算机或编译器是无法完全使用线程。

根据 gcc 版本,您应该添加编译器开关 -std=c++11 或 -std=c++0x。

我可以编译它here

使用 C++14 并得到如下输出。

task1 says: Hello

使用 -std=c++11 标志或更高版本编译。