在ppl中向任务传递参数

  • 本文关键字:参数 任务 ppl c++ ppl
  • 更新时间 :
  • 英文 :


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

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

不能传递任何参数给它。我该怎么做呢?如果我尝试将参数传递给lambda,我会得到编译错误。

传递给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; }

这个链接给出了一个传递字符串给任务的好例子。

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;
});

最新更新