equivalent of c++ private inheritance with using

Dan dbdavidson at yahoo.com
Sun Oct 14 05:08:11 PDT 2012


On Friday, 12 October 2012 at 23:05:27 UTC, Jonathan M Davis 
wrote:

> You can have the variable be private and alias a function which 
> returns by ref
> instead of the variable itself. Something like
>
> class C
> {
>  @property ref inout(Impl) get() inout { return _impl; }
>  alias get this;
>
> private:
>  Impl _impl;
> }
>
> - Jonathan M Davis

Thanks, that is interesting, but is it the same? I don't think 
that this then provides any encapsulation? The idea is the client 
gets no access to Impl methods unless I say so and I say so with 
a using declaration. Then you can introduce more functionality, 
so it is implementation inheritance. It might not be possible to 
get the exact same thing, since the RateCurve struct is not 
really Array!DateValue, it just looks like it with the alias. The 
closest I can get is to alias each of what is needed and add 
forwarding functions. So, for example, with this new RateCurve, 
clients can call insert() but not call clear().

struct RateCurve {
   alias Array!DateRate ContainerType;
   alias ContainerType.Range Range;
   alias _impl this;

   size_t insert(Stuff)(Stuff stuff) {
     enforce(_impl.empty || (stuff.when >= _impl.back.when),
             text("Can not insert items out of order ",
                  _impl.back, " is newer than ", stuff));

     return _impl.insert(stuff);
   }

   DateRate getRate(Date asOf) {
     auto needle = DateRate(asOf, 0);
     if(!_impl.empty) {
       auto sortedRage = assumeSorted!("a.when <= b.when", 
Range)(opSlice());
       auto lowerBound = sortedRage.lowerBound(needle);
       if(!lowerBound.empty) {
         needle = lowerBound.back;
       }
     }
     return needle;
   }

   Range opSlice() { return _impl.opSlice(); }

   this(U)(U[] values...) if (isImplicitlyConvertible!(U, 
DateRate)) {
     foreach (value; values) {
       insert(value);
     }
   }

private:
   ContainerType _impl;
}




More information about the Digitalmars-d-learn mailing list