logical const without casts!

Marco Leise Marco.Leise at gmx.de
Fri Sep 30 10:07:14 PDT 2011


Am 29.09.2011, 16:54 Uhr, schrieb Steven Schveighoffer  
<schveiguy at yahoo.com>:

> I just thought of an interesting way to make a logical const object  
> without casts.  It requires a little extra storage, but works without  
> changes to the current compiler (and requires no casts).
>
> Here's the code, then I'll talk about the implications:
>
> import std.stdio;
>
> class D
> {
>      D getme() { return this;}
>      void foo() {writeln("mutable!");}
> }
>
> class C
> {
>      D delegate() d;
>      this()
>      {
>        auto dinst = new D;
>        this.d = &dinst.getme;
>      }
>      void bar() const { d().foo();}
> }
>
> void main()
> {
>      auto c = new C;
>      c.bar();
> }
>
> [...]
>
> What do people think about this?
>
> -Steve

I think this is a creative use of delegates!

--------

class Vendor {
	void sell() {
		++_sold;
	}

	@property
	int sold() {
		return _sold;
	}

private:
	int _sold = 1;
}

class Car {
	this(Vendor vendor) {
		_vendorDlg = () { return vendor; };
	}

	Vendor getVendor() const {
		return _vendorDlg();
	}

private:
	Vendor delegate() _vendorDlg;
}

void main(string[] args) {
	immutable Car car = new immutable(Car)(new Vendor());
	Vendor vendor = car.getVendor();
	vendor.sell();
}


More information about the Digitalmars-d mailing list