www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Propagating constness through function results

reply David Zhang <straivers98 gmail.com> writes:
Hi,

I have a class `Image`, and I have a function called 
`getSubImage(Rect bounds)`. What I can't figure out is how to get 
the result of `getSubImage()` to take on the constness of the 
backing image.

ie.
     //The Image class is really just a view over a buffer that's 
managed elsewhere
     const(Image).getSubImage(...) -> const(Image)

     Image.getSubImage(...) -> Image

I tried to do this with `inout`, but that requires that a 
parameter in the function be `inout`. I don't suppose I could 
somehow declare `this` to be inout?

Thanks
Sep 17 2017
parent reply David Zhang <straivers98 gmail.com> writes:
On Sunday, 17 September 2017 at 21:18:08 UTC, David  Zhang wrote:
 Hi,

 I have a class `Image`, and I have a function called 
 `getSubImage(Rect bounds)`. What I can't figure out is how to 
 get the result of `getSubImage()` to take on the constness of 
 the backing image.

 ie.
     //The Image class is really just a view over a buffer 
 that's managed elsewhere
     const(Image).getSubImage(...) -> const(Image)

     Image.getSubImage(...) -> Image

 I tried to do this with `inout`, but that requires that a 
 parameter in the function be `inout`. I don't suppose I could 
 somehow declare `this` to be inout?

 Thanks
I am aware that you can duplicate the method, but it seems a bit unwieldy and excessive.
Sep 17 2017
parent reply David Zhang <straivers98 gmail.com> writes:
Nevermind! I rediscovered the `inout`attribute.

Though if I may say so, I have no idea how `inout` is supposed to 
indicate "whatever the constness of a".
Sep 17 2017
parent Steven Schveighoffer <schveiguy yahoo.com> writes:
On 9/17/17 5:37 PM, David Zhang wrote:
 Nevermind! I rediscovered the `inout`attribute.
Correct, inout applied to the function is actually applying to the 'this' parameter. Same as const or immutable functions as well.
 
 Though if I may say so, I have no idea how `inout` is supposed to 
 indicate "whatever the constness of a".
 
What inout does is look at the mutability of the parameter and transfer it to the mutability of the return type. -Steve
Sep 17 2017