0

我刚刚开始在 Visual Studio 中学习 ppl,并开始学习任务。到目前为止一切顺利,例如我确实了解基础知识。但是如何创建接收参数的任务?也就是说,创建不带参数的任务相当简单,但带任何参数的任务对我来说根本不明显。
任务不带任何参数的任务创建很容易:

task<string> aTask{ create_task([]() {
        return string{};
            } 
              )
            };  

不能真正传递任何参数给它。我该怎么办。如果我尝试将参数传递给 lambda,则会出现编译错误。

4

2 回答 2

0

您传递给 create_task 的参数可以是您在代码中演示的 lambda 函数。

那么问题就变成了如何将参数传递给 lambda 函数。

以下是几种 lambda:

// basic lambda
auto func = [] () { cout << "A basic lambda" ; } ;

// lambda where variable is passed by value
auto func = [](int n) { cout << n << " "; }

// lambda where variable is passed by refrence
auto func = [](int& n) { cout << n << " "; }

// lambda with capture list
int x = 4, y = 6;
auto func = [x, y](int n) { return x < n && n < y; }

// lambda that explicitly returns an int type
auto func = [] () -> int { return 42; }
于 2015-10-22T08:12:20.640 回答
-1

此链接提供了将字符串传递给任务的一个很好的示例。

https://msdn.microsoft.com/en-us/library/dd492427.aspx

示例代码是

return create_task([s] 
{
    // Print the current value.
    wcout << L"Current value: " << *s << endl;
    // Assign to a new value.
    *s = L"Value 2";
}).then([s] 
{
    // Print the current value.
    wcout << L"Current value: " << *s << endl;
    // Assign to a new value and return the string.
    *s = L"Value 3";
    return *s;
});
于 2017-04-24T19:08:47.170 回答