rvalue types

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Mar 12 19:03:10 UTC 2018


On Mon, Mar 12, 2018 at 06:46:56PM +0000, Simen Kjærås via Digitalmars-d wrote:
> On Monday, 12 March 2018 at 16:51:06 UTC, H. S. Teoh wrote:
> > I suspect the current language already supports this, or is 90% of
> > the way there and just needs some small concessions on syntax.  For
> > example, today you can already make opBinary() return something
> > other than the parent type, and use alias this to make it decay to
> > the parent type. Of course, this requires the caller to write
> > `BigInt x = a^^b % c` rather than `auto x = a^^b % c`, but I think
> > that's a minor inconvenience.
> 
> I mostly agree, but it can play havoc on generic code. On the other
> hand, if we don't think carefully through how they should work, so
> would rvalue types.
[...]

Actually, I'm even wondering if allowing the assignment of an
intermediate type might not necessarily be a bad thing.  Suppose
BigInt.opBinary returns some intermediate type, like BigIntIntermediate,
that implicitly converts to BigInt via alias this.  If you write:

	BigInt a, b, c;
	auto x = a*b + c;

then x will be a BigIntIntermediate instead of a BigInt. But is that
really so bad?  It can participate in further BigInt operations,
returning more instances of BigIntIntermediate, and only when you
actually try to do something to it, like assign it to a BigInt variable
or return it from a function with BigInt return type, will the implicit
conversion (and presumably the actual computation) happen.  I'd say this
is even a *good* thing, because then:

	BigInt x = a*b + c;

will actually be equivalent to:

	auto tmp = a*b;
	BigInt x = tmp + c;

and the latter will actually have the same optimizations as the
single-expression case!  So essentially, BigIntIntermediate becomes a
lazy type that only performs the computation when it's actually
necessary, and in the meantime it can accumulate knowledge of what's
being computed so that it can optimize expensive operations.


T

-- 
The richest man is not he who has the most, but he who needs the least.


More information about the Digitalmars-d mailing list