3

Is there a way to simplify the following code to avoid the .then call that "converts" my task<int> to task<void>?

I can't change the function signature of MyClass::MyFunction1 because it's a part of a public API.

task<void> MyClass::MyFunction1()
{
    return MyFunction2().then([](int) {});
}

task<int> MyClass::MyFunction2()
{
    // Some code here
}
K Mehta
  • 9,689
  • 4
  • 41
  • 69

1 Answers1

1

concurrency::task is a template class, therefore concurrency::task<int> and concurrency::task<void> are two different classes. Instances of either cannot be cast or converted to the other.

Therefore your approach is somewhat correct. However, you're not converting, you're simply creating a new task<void> instance, which will be executed by the task<int> returned by Method2() after it is done. That hides a little bit what you're actually trying to do, and might make it harder to maintain the code in the future. I would think a better approach is to create and return a task<void> that encapsulates Method2() and waits for it's completion:

concurrency::task<void> MyFunction1()
{
    return concurrency::task<void>{[]()
    {
        MyFunction2().wait();
    }};
}

This is a bit more straight forward and clean, especially since the task<void> that the caller receives actually executes whatever MyFunction2() is executing.

Either way, since the types are not compatible, there is no way around creating a new task<void> instance.

Max Vollmer
  • 8,102
  • 9
  • 27
  • 43