On Tue, 10 Jul 2012 21:27:54 +0200, Namespace <rswhi...@googlemail.com> wrote:

Maybe D need's a readonly keyword.
Sometimes i have a class which can take an object from everywhere to store it. So it can not be const, because i didn't just initialized it with a ctor. But i don't want to change the object, i only want to read or call const methods. What now?
I'd suggest a readonly keyword for that.

[code]
class Foo {
readonly:
     Bar _b;

public:
void SetBar(readonly Bar b) {
     _b = b;
}
}
[/code]

Or has D an alternative?

If Bar is a class, use std.typecons.Rebindable.

Otherwise, it's hairier. What should readonly mean?

From what I see, it provides const access, and is reassignable. This is easily implemented in user code today:

import std.traits;

struct Readonly( T ) {
    private T payload;

    this( Unqual!T value ) {
        payload = value;
    }

    auto opAssign( const T value ) {
        payload = cast()value;
        return this;
    }

    @property
    const(T) get( ) const {
        return payload;
    }

    alias get this;
} unittest {
    struct S {
        int n;

        void foo() {}
        void bar() const {}
    }

    Readonly!S a;
    a = S( 3 );
    assert( a.n == 3 );
    assert( !__traits( compiles, a.n = 4 ) );
    assert( !__traits( compiles, a.foo() ) );
    assert( __traits( compiles, a.bar() ) );
}

Reply via email to