On Thursday, 15 November 2012 at 13:54:10 UTC, Joseph Rushton
Wakeling wrote:
Make 'void check()' be 'void check() const'
Thanks
Dan
The following code refuses to compile:
///////////////////////////////////////////////////////
import std.math;
struct Foo
{
int a;
int b;
this(int a, int b)
{
this.a = a;
this.b = b;
}
void check()
{
real c = (a ^^ 2 + b ^^ 2) ^^ 0.5;
assert(c < 10);
}
}
void main()
{
auto foo = cast(immutable) Foo(3, 4);
foo.check();
}
///////////////////////////////////////////////////////
... producing an error message: immustruct.d(25): Error:
function immustruct.Foo.check () is not callable using argument
types () immutable
The reason seems pretty evident -- making the instance
immutable means that the temporary internal variable c in
check() can't be (over)written. At the same time, this feels a
bit daft -- you're talking about a transient value that is
never seen outside the function scope.
Is there any way of getting round this constraint so such
temporary, transient variables are still permitted within
methods of an immutable instance?
As a workaround, if I write a function external to Foo, e.g.
void check2(Foo foo)
{
real c = (foo.a ^^ 2 + foo.b ^^ 2) ^^ 0.5;
assert(c < 10);
}
... then calling foo.check2() runs without problem. I'm just
curious as to whether it can be done within a struct method too.