0

I'm just beginning to learn ppl in Visual Studio and I began learning about tasks. So far so good, and for example I do understand the basics. But how can I create task that receives an argument? That is, it is fairly straightforward to create task which takes no arguments, but one that takes any arguments is not obvious to me at all.
Task creation where task does not take any arguments is easy:

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

Cannot really pass any arguments to it. How would I go about it. If I try to pass arguments into lambda I'm getting compilation error.

Artur
  • 181
  • 1
  • 9
  • What exact error are you getting? It is hard to say anything definite without a full sample. – Tony Jan 09 '17 at 01:19

2 Answers2

0

The parameter that you pass into create_task can be a lambda function as you demonstrate in your code.

So then the question becomes how to pass parameters into lambda functions.

Here are a few varieties of 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; }
dspfnder
  • 1,049
  • 1
  • 8
  • 12
  • 2
    Thank you for your answer, but this really doesn't answer the OQ. I know how to pass arguments to a lambda but if I try to do it from the task I am getting error messages. So it is not as simple as it may look. – Artur Oct 22 '15 at 08:20
-1

This link gives a good example of passing a string to a task.

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

Example code is

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;
});
Trident
  • 718
  • 8
  • 18