Const vs Non const method

Rene Zwanenburg via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Feb 25 02:59:43 PST 2016


On Thursday, 25 February 2016 at 10:44:49 UTC, Andrea Fontana 
wrote:
> Check this simple code:
> http://dpaste.dzfl.pl/2772c9144f1c
>
> I can't understand how to minimize code duplication for 
> function like get().
> Of course on real case body is much bigger and complex than 
> that.
>
> The only way I found is to move the body of function inside a 
> mixin template:
>
> mixin template getterImpl()
> {
>    auto getterImpl() { /* very long body */ return inner; }
> }
>
> and then:
>
> auto get() const { mixin getterImpl; return getterImpl; }
> auto get() { mixin getterImpl; return getterImpl; }
>
> Am I missing something? I don't think it's the right way.

You can do this using inout:
http://dpaste.dzfl.pl/678cac023051

That getter can be written even shorter due to a quirk in the D 
syntax, like:

inout get() { return inner; }

But I prefer to explicitly state inout for every parameter and 
return type.

inout is kind of a wildcard for mutable, const, and immutable. 
You can also add it to your function parameters, for example:

inout(int[]) doSomething(inout(SomeClass) c);

So the constness of doSomething's return type depends on the 
constness of the passed argument.


More information about the Digitalmars-d-learn mailing list