self-referential invariant member
Denton Cockburn
diboss at hotmail.com
Fri Feb 8 04:52:58 PST 2008
On Wed, 06 Feb 2008 22:57:53 +0900, Neil Vice wrote:
> I am attempting to provide a constant instance of a struct as a member of
> the struct (in 2.010) and am getting unexpected compiler errors. Can someone
> explain what the compiler thinks I'm trying to do here and/or how I'd go
> about achieving what I want if it's possible?
>
> The following code:
>
> struct Test
> {
> public invariant Test Default;
> }
>
> void main()
> {
> Test test = Test.Default;
> }
>
> produces the following compiler output:
>
> test.d(3): struct test.Test unable to resolve forward reference in
> definition
>
> Similarly if Test is declared as a class not a struct the compiler produces
> the following:
>
> test.d(9): Error: 'this' is only allowed in non-static member functions,
> not main
> test.d(9): Error: this for Default needs to be type Test not type int
> test.d(9): Error: cannot implicitly convert expression (this.Default) of
> type invariant(Test) to test.Test
>
> If Default is declared as a manifest constant using the enum keyword the
> compiler gets a stack overflow (bug #1800).
>
> If I attempt to initialise Default (where Test is a struct), the compiler
> makes reference to opCall:
>
> public invariant Test Default = {};
>
> yields:
>
> test.d(9): Error: no property 'opCall' for type 'Test'
> test.d(9): Error: function expected before (), not 1 of type int
> test.d(9): Error: cannot implicitly convert expression (1(Default)) of
> type int to Test
You need to define your struct with a static opCall to handle an invariant
Test:
Also, Default has to be declared static.
struct Test
{
public static invariant Test Default;
static Test opCall(invariant Test t) { // create, do stuff to, and return
struct }
}
I think that opCall will have to be set up to copy that Default;
Isn't what you want a ref to that Default struct? I thought assigning
a struct is equivalent to copying it.
I got it to compile doing what I just did.
So again, are you trying to have copies of the Default, or just one copy?
More information about the Digitalmars-d-learn
mailing list