C++ Logo

std-proposals

Advanced search

Re: Do we need a way to take *this by value, for coroutines?

From: Phil Endecott <std_proposals_list_at_[hidden]>
Date: Mon, 08 Nov 2021 13:30:06 +0000
Giuseppe D'Angelo wrote:
> On 07/11/2021 19:04, Phil Endecott via Std-Proposals wrote:
>>
>> We have ref-qualifiers that allow us to indicate whether a method
>> takes *this as an rvalue or lvalue reference, but this mechanism
>> doesn't allow it to be taken by value.
>
> This should be solved by the "Deducing this" proposal (P0847), which I
> believe has just been voted into C++23. Under the syntax introduced by
> that paper, you can finally pass `*this` by value to non-static member
> functions.

Ah yes, thanks for reminding me about that proposal.
I see now it is actually an example in section 5.4.3, "For lifetime
management of coroutines".

Quoting Marcin's example:

text_generator_t text(this F self) //no `&`!
{
  for (auto c: *(self.p)) co_yield c;
}

I do wonder why it needs to introduce the parameter name "self",
and can't simply keep the concise syntax in the body, i.e.

text_generator_t text(F this)
{
  for (auto c: *p) co_yield c; // p is this.p
}



Anyway, I realised after posting that the following works:

class example {

static generator_t static_foo(example the)
{
  ... co_yield ...
}

generator_t foo()
{
  return static_foo(*this);
}

};

It took me a while to realise this because here we have a function
whose return type is generator_t but it is not itself a coroutine.
I wasn't at all sure if that was legitimate, but I now think it is.


Regards, Phil.

Received on 2021-11-08 07:30:12