On 01/16/2010 02:01 PM, aarti_pl wrote:
W dniu 2010-01-16 13:26, Simen kjaeraas pisze:
aarti_pl <[email protected]> wrote:


class Test {
string t1 = "test"; //Ok!
char[] t2 = "test".dup; //Compile error
}

void main(char[][] args) {
}

Error:
hello.d(3): Error: cannot evaluate _adDupT((&
D12TypeInfo_Aya6__initZ),"test") at compile time
hello.d(3): Error: cannot evaluate _adDupT((&
D12TypeInfo_Aya6__initZ),"test") at compile time

Is there workaround?

Constant strings are saved in the static data segment of the
executable, so
the .dup call would need to be executed at runtime. In other words, what
this would do is cast const to mutable.

If this did compile, changing the contents of t2 would change those
contents
for all instances of Test, which I assume is not your intention.

As for the workaround, write a constructor:

class Test {
string t1 = "test";
string t2;

this( ) {
t2 = "test".dup;
}
}


I want just simple initialization of variable. Casting of course is no
(sane) option.

Indeed, in case of classes your workaround will work.

But in case of struct? The same problem occurs for structs, but you can
not declare default constructor in structs...

IMHO .dup should work for initialization of classes/structs.

Any other ideas?

BR
Marcin Kuszczak
(aarti_pl)

Perhaps this is or should be a bug. You can override dup to work in ctfe:

char[] dup(string str)
{
    return str.dup;
}

class Test {
    string t1 = "test";        //Ok!
    char[] t2 = "test".dup;    //Compile error
    char[] t3 = "test".dup();  //Ok!
}

The spec even mentions it under ctfe:

6. as a special case, the following properties can be executed at compile time:
.dup
.length
.keys
.values

http://www.digitalmars.com/d/2.0/function.html




Reply via email to