alias this private?

Ali Çehreli acehreli at yahoo.com
Sun Dec 9 08:50:54 PST 2012


On 12/09/2012 01:42 AM, js.mdnq wrote:

 > Actually, it doesn't seem to work ;/ Your code worked but mine does
 > unless I make it public. It is a public/private issue and I get a ton of
 > errors:

This is not adding to the discussion much but it is again because the 
member is private. writeln() is in a separate module, which cannot 
access a private member of another module. (Actually it is 
std.traits.isImplicitlyConvertible that can't access that member.):

class A
{
     struct B(T)
     {
     private:
         //public:
         T Value;
     public:
         alias Value this;

         T opAssign(F)(F v)
         {
             //writeln(Name ~ " ...");
             Value = cast(T)v;
             return Value;
         }
     }

     B!int b;
}

// Copied from isImplicitlyConvertible
template isImplicitlyConvertible_LOCAL(From, To)
{
     enum bool isImplicitlyConvertible_LOCAL = is(typeof({
         void fun(ref From v)
         {
             void gun(To) {}
             gun(v);
         }
     }));
}

import std.traits;

int main(string[] argv)
{

     A c = new A();

     c.b = 34;

     static assert(isImplicitlyConvertible_LOCAL!(A.B!int, int)); // PASSES
     static assert(isImplicitlyConvertible      !(A.B!int, int)); // FAILS

     return 0;
}

 > So while it might "work" in the simple case it doesn't seem to actually
 > work...

I am not sure that it should work. If it is private, maybe it should 
stay private.

What you seem to need is read-only access to a private member. There are 
other ways of achieving that. The following program uses both a 
read-only property function and an 'alias this':

module main;

import std.stdio;

class A
{
     struct B(T)
     {
     private:
         //public:
         T Value_;
     public:

         // read-only accessor
         T Value() const @property
         {
             return Value_;
         }

         // Automatic conversion to the read-only accessor
         alias Value this;

         T opAssign(F)(F v)
         {
             //writeln(Name ~ " ...");
             Value_ = cast(T)v;
             return Value_;
         }
     }

     B!int b;
}

int main(string[] argv)
{

     A c = new A();

     c.b = 34;
     writeln(c.b);
     getchar();
     return 0;
}

Ali



More information about the Digitalmars-d-learn mailing list