【问题标题】:Passing a parameter to a task in ppl将参数传递给 ppl 中的任务
【发布时间】:2015-10-22 07:56:53
【问题描述】:

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

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

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

【问题讨论】:

  • 你得到了什么确切的错误?如果没有完整的样本,很难说任何确定的事情。

标签: c++ ppl


【解决方案1】:

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

【讨论】:

  • 感谢您的回答,但这确实不能回答 OQ。我知道如何将参数传递给 lambda,但如果我尝试从任务中执行此操作,我会收到错误消息。所以它并不像看起来那么简单。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2015-04-16
    • 1970-01-01
    • 2017-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多