Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to say Hello World with C++20 coroutine?

Just for learning purpose I've tried to make overcomplicated "Hello World" program with C++20 coroutines:

HelloWorldMessage sayHelloToWorld()
{
    co_yield "Hello";
    co_yield " ";
    co_yield "World";
    co_yield "!";
}

int main() 
{
    for (auto w : sayHelloToWorld())
    {
        std::cout << w;
    }
}

To prepare such HelloWorldMessage generator I based mainly on latest clang warning messages and, uncomplete cppreference page and this example.

So my result below. What is missing here? Because, instead of saying Hello, I got segmentation fault:

See link:

struct HelloWorldState
{
    const char* currentWord = "<not value yet>";
    bool finalWord = false;
};

struct HelloWorldPromise
{
    HelloWorldState state;
    std::experimental::suspend_always initial_suspend() const noexcept { return {}; }
    std::experimental::suspend_always final_suspend() const noexcept { return {}; }

    std::experimental::suspend_always yield_value(const char* word) noexcept
    {
        state.currentWord = word;
        return {};
    }  

    std::experimental::suspend_always return_void() noexcept
    {
        state.finalWord = true;
        return {};
    }  

    auto& get_return_object() noexcept
    {
        return *this;
    }

    void unhandled_exception()
    {
        state.finalWord = true;
        throw;
    }
};

struct HelloWorldMessage
{
    using promise_type = HelloWorldPromise;
    using promise_handle = std::experimental::coroutine_handle<promise_type>;

    struct Iter
    {
        promise_handle handle = nullptr;
        HelloWorldState state;

        using iterator_category = std::input_iterator_tag;
        using value_type        = const char*;
        using difference_type   = ptrdiff_t;
        using pointer           = value_type const *;
        using reference         = value_type const &;

        reference operator * () const { assert(handle); return state.currentWord; }
        pointer operator -> () const { return std::addressof(operator*()); }

        bool operator == (const Iter& other) { return handle == other.handle; }
        bool operator != (const Iter& other) { return !(*this == other); }

        Iter() = default;
        Iter(promise_handle handle)
            : handle(handle)
        {
           assert(handle);
           next();
        }

        Iter& operator ++()
        {
            if (!handle)
                return *this;
            if (state.finalWord)
            {
                handle = nullptr;
                return *this;
            }
            next();
            return *this;
        }

        void next()
        {
            try {
                handle.resume();
                state = handle.promise().state;
            } catch (...) {
                std::cerr << "@%$#@%#@$% \n";
            }
        }

    };

    promise_handle handle = nullptr;
    HelloWorldMessage(promise_type& promise) : handle(promise_handle::from_promise(promise)) {}

    Iter begin() const { assert(handle); return {handle}; }
    Iter end() const { return {}; }
};

Maybe clang is not ready yet?

like image 702
PiotrNycz Avatar asked Oct 15 '22 15:10

PiotrNycz


1 Answers

A few mistakes:

First - promise shall return generator object, not reference to itself. So the proper way is:

struct HelloWorldPromise
{
    ...
    auto get_return_object();
    ...        
};

struct HelloWorldMessage
{
    ...
};

auto HelloWorldPromise::get_return_object()
{
    return HelloWorldMessage(*this);
}

Next - terminate and return void can be simplified to:

void return_void() noexcept
{}  
void unhandled_exception()
{
    std::terminate();
}

Next - in iterator - we shall rely on handle.done - so the state.finalWord is not needed. Full iterator source is:

struct Iter
{
    promise_handle handle = nullptr;
    HelloWorldState state;

    reference operator * () const { return state.currentWord; }
    pointer operator -> () const { return std::addressof(operator*()); }

    bool operator == (const Iter& other) const { return !handle == !other.handle; }
    bool operator != (const Iter& other) const { return !(*this == other); }

    Iter() = default;
    Iter(promise_handle handle)
        : handle(handle)
    {
       next();
    }

    Iter& operator ++()
    {
        if (!handle)
            return *this;
        next();
        return *this;
    }

    void next()
    {
        if (!handle)
            return;
        try {
            handle.resume();
            if (!handle.done())
               state = handle.promise().state;
            else {
                handle = nullptr;
            }
        } catch (...) {
            std::cerr << "@%$#@%#@$% \n";
        }
    }

};

And full working example here.

I take most of my corrections from this 2018/n4736.pdf.

like image 77
PiotrNycz Avatar answered Nov 15 '22 08:11

PiotrNycz