On Thursday, 25 February 2016 at 10:59:43 UTC, Rene Zwanenburg
wrote:
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.
What would be the C++ way? Is there any comfortable way to solve
this problem in a nice way like D?