UnclePooh
UnclePooh

Reputation: 78

C++ / WinRT Coroutine does not compile due to problem with type conversion

I've started to use C++/WinRT and I want to implement coroutine which call function "LaunchFileAsync". But my code doesn't compile and I have no idea why.

#include <pch.h>
#include <winrt/Windows.System.h>
#include <winrt/Windows.Storage.h>

using namespace winrt;
using namespace Windows::System;
using namespace Windows::Storage;
using namespace Windows::Foundation;

Windows::Foundation::IAsyncOperation<bool> ActionOnClick()
{
    const auto uri = Uri(L"URI");
    const auto storageFile{ co_await StorageFile::GetFileFromApplicationUriAsync(uri) };

    co_return Launcher::LaunchFileAsync(storageFile);
}

According to the https://learn.microsoft.com/en-us/uwp/api/windows.system.launcher.launchfileasync?view=winrt-18362, Launcher::LaunchFileAsync returns IAsyncOperation, but the compiler give the following error:

1>E:ExamplesConsoleApplication1\ConsoleApplication1\main.cpp(16,1): error C2664: "void std::experimental::coroutine_traits<winrt::Windows::Foundation::IAsyncOperation<bool>>::promise_type::return_value(const TResult &) noexcept": argument 1 cannot be converted from "winrt::Windows::Foundation::IAsyncOperation<bool>" to "TResult &&"
1> with
1> [
1> TResult=bool
1> ]
1>E:Examples\ConsoleApplication1\ConsoleApplication1\main.cpp(16,1): message : Cause: Can't be converted from "winrt::Windows::Foundation::IAsyncOperation<bool>" to "TResult"
1> with
1> [
1> TResult=bool
1> ]
1>E:\Examples\ConsoleApplication1\ConsoleApplication1\main.cpp(16,40): message : No user-defined conversion operator is available to perform this conversion or the operator cannot be called

What's the problem?

Upvotes: 1

Views: 937

Answers (1)

IInspectable
IInspectable

Reputation: 51345

The code is attempting to return an awaitable object rather than the value it returns. You will have to co_await the result first before you can co_return it:

Windows::Foundation::IAsyncOperation<bool> ActionOnClick()
{
    const auto uri = Uri(L"URI");
    const auto storageFile{ co_await StorageFile::GetFileFromApplicationUriAsync(uri) };

    auto const result{ co_await Launcher::LaunchFileAsync(storageFile) };
    co_return result;
}

Upvotes: 1

Related Questions