On Sunday, 30 September 2018 at 09:30:38 UTC, Vijay Nayar wrote:
Is there a way to either have a constant reference to a class
that can be set to a new value, or is there a way to convert
the class variable to a class pointer?
For example:
void main()
{
class Thing {}
class ThingSaver {
// A const(Thing) could not be changed in
setThing().
const(Thing)* t;
void setThing(in Thing thing) {
t = thing; // ERROR converting to pointer type!
}
const(Thing) getThing() const {
return *t;
}
}
Thing t1 = new Thing();
ThingSaver saver = new ThingSaver();
saver.setThing(t1);
const(Thing) t2 = saver.getThing();
}
I think, what you are facing here, is the different notion of
const, as used from C++. The reasoning about it is described for
example here:
http://jmdavisprog.com/articles/why-const-sucks.html
Jonathan is much better therein as I am.
However, there are approaches to solve what you want to do. For
example, there is a Rebindable around:
https://dlang.org/library/std/typecons/rebindable.html
´´´
import std.stdio;
import std.typecons;
void main()
{
class Thing {int dummy; }
class ThingSaver {
/*
A const(Thing) could not be changed in setThing(),
but a Rebindable can be reassigned, keeping t const.
*/
Rebindable!(const Thing) t;
void setThing(in Thing thing) {
t = thing; // No pointers in use :)
}
const(Thing) getThing() const {
return t;
}
}
Thing t1 = new Thing();
ThingSaver saver = new ThingSaver();
saver.setThing(t1);
//saver.t.dummy = 5; fails as expected.
const(Thing) t2 = saver.getThing();
}
´´´
I hope, I got your idea right...