Is there a way to return an lvalue and also an rvalue from the same member function?

Steven Schveighoffer schveiguy at
Sun Sep 20 14:54:09 UTC 2020

On 9/20/20 9:30 AM, realhet wrote:
> Hi,
> struct S{
>    int[2] array;
>    ref  x()       { return array[0]; }
>    auto x() const { return array[0]; }
> }
> If there a way to write the function 'x' into one function, not 2 
> overloads.
> I tried auto/const/ref mindlessly :D, also remembered 'inout', but 
> obviously those weren't solve the problem.

Your original code is an odd situation -- you want to return by ref if 
it's mutable, but not if it's const?

Why not return by ref always, and just forward the constancy? This is 
what inout is made to do:

ref inout(int) x() inout { return array[0]; }

> (This is going to be a swizzling 'system' that mimics GLSL, later I will 
> make a template that takes 'x'as a template parameter, just wondering 
> that the support for const and non-cons can be done easier.)

If you want to differ behavior by const, but write one function, you can 
use a `this` template parameter. But without seeing your real use case, 
you might end up writing the same amount of code.


More information about the Digitalmars-d-learn mailing list