const - How can I return imutable reference types without break constness? -
i have following code in d:
import std.stdio; import std.container.array; class reftype { } class mycontainer { private array!reftype test; reftype result() const { // want const on this, not on return type return test[0]; // use opindex() array(t) // error: cannot implicitly convert expression (this.test.opindex(0u)) // of type const(reftype) main.reftype } } int main(string[] argv) { auto c = new mycontainer; auto r = c.result(); return 0; }
as can see want return reference type custom container class. opindex() of array not giving permission that, why?
i think opindex()
should return reftype
instead of const(reftype)
value because array array!reftype
.
is bug? or design intention? if intented design, how can want?
i think opindex() should return reftype instead of const(reftype) value because array array!reftype.
no, wrong. when define memthod const
, have specified members of class const. means that, no matter type member has in definition, inside result
method (at least) const
. such, compiler justified in returning error returning.
the usual (e.g. c++
) way resolve define 2 (or, in d, three) overloads:
reftype result() { return test[0]; } reftype result() const { return test[0]; } reftype result() immutable { return test[0]; }
so, 1 case class mutable, returns mutable reference. 1 case class const, returns const reference, , 1 case class immutable, returns immutable reference.
you notice, however, aside method decoration, 3 implementations precisely same. prevent defining 3 identical implementations, d
has inout
modifier:
reftype result() inout { return test[0]; }
this single definition replaces 3 of definitions above. rule of thumb, write definition usual, place inout
place you'd otherwise place const
.
Comments
Post a Comment