An Hoa An Hoa - 1 month ago 34
C++ Question

co_await not working

I attempted to try out

co_await
as mentioned in this article https://blogs.msdn.microsoft.com/vcblog/2016/04/04/using-c-coroutines-to-simplify-async-uwp-code/ but there are weird compilation errors:

C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\experimental\resumable(44,0): Error C2825: '_Ret': must be a class or namespace when followed by '::' (compiling source file MainPage.xaml.cpp)
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\experimental\resumable(44): error C2825: '_Ret': must be a class or namespace when followed by '::' (compiling source file MainPage.xaml.cpp)
MainPage.xaml.cpp(44): note: see reference to class template instantiation 'std::experimental::coroutine_traits<void,::MainPage ^,Windows::UI::Xaml::Navigation::NavigationEventArgs ^>' being compiled
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\experimental\resumable(44,0): Error C2510: '_Ret': left of '::' must be a class/struct/union (compiling source file MainPage.xaml.cpp)
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\experimental\resumable(44): error C2510: '_Ret': left of '::' must be a class/struct/union (compiling source file MainPage.xaml.cpp)
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\experimental\resumable(44,0): Error C2061: syntax error: identifier 'promise_type' (compiling source file MainPage.xaml.cpp)
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\experimental\resumable(44): error C2061: syntax error: identifier 'promise_type' (compiling source file MainPage.xaml.cpp)
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\experimental\resumable(44,0): Error C2238: unexpected token(s) preceding ';' (compiling source file MainPage.xaml.cpp)


Originally, I put the following code in the constructor

#include <experimental\resumable>
#include <pplawait.h>

using namespace concurrency;

MainPage::MainPage()
{
InitializeComponent();

auto my_data_file = co_await Windows::ApplicationModel::Package::Current->InstalledLocation->GetFileAsync("samples.txt");

// Preparing app data structures
}


which does not work. My guess is that this is not possible in constructor (for obvious reason) so I move the
co_await
line to

void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
{
auto my_data_file = co_await Windows::ApplicationModel::Package::Current->InstalledLocation->GetFileAsync("samples.txt");
}


which result in the aforementioned compilation errors.

Answer

My guess is that the first problem is that you can't return void from a resumable function since void does not fill any coroutine traits that co_await expect (like get_return_object , set_result etc.)

if you are already using PPL, return task<void>:

task<void> MainPage::OnNavigatedTo(NavigationEventArgs^ e)
{
    auto my_data_file = co_await Windows::ApplicationModel::Package::Current->InstalledLocation->GetFileAsync("samples.txt");
}