Logical const

Simen kjaeraas simen.kjaras at gmail.com
Mon Nov 29 17:24:45 PST 2010


Jesse Phillips <jessekphillips+D at gmail.com> wrote:

> In fact, couldn't opAssign be
>
>
>      ref opAssign(U)(auto ref U v)  if(Unqual!U == U)
>      {
>          return mutable() = v;
>      }
>
> This way only mutable references are only ever assigned to it? Then it  
> can be marked as @trusted and used in safe code as it will never cause  
> the program to crash?

Indeed it could. This brings me to this code:


struct Mutable( T ) if ( is( T : Unqual!T ) ) {
     private T _payload;

     this( Unqual!T t ) {
         _payload = t;
     }

     @trusted @property ref T get( )( ) const {
         T* p = cast( T* )&_payload;
         return *p;
     }
     alias get this;

     @trusted ref opAssign( U )( auto ref U u ) const if ( is( Unqual!U ==  
U ) && is( U : T ) ) {
         T* p = cast( T* )&_payload;
         return *p = u;
     }

     bool opEquals( )( ref const Mutable other ) const {
         return _payload == other._payload;
     }

     bool opEquals( U )( auto ref U other ) const if ( is( U : T ) || is( T  
: U ) ) {
         return _payload == other;
     }
}

It works in many cases, but not for function calls:

void bar( int n ) {}

class A {
     Mutable!int n;
}

A a = new A;
bar(a.n);//Error: function bar (int n) is not callable using argument  
types (const(Mutable!(int)))


-- 
Simen


More information about the Digitalmars-d mailing list