Re: Why does this not compile?

2018-03-06 Thread Diego via Digitalmars-d

On Tuesday, 6 March 2018 at 10:03:54 UTC, Shachar Shemesh wrote:

void main() {
struct S {
uint value;

~this() {
}
}

const S a = S(12);
S b = a;
}



You cannot assign a const element (`a`) to a non-const element 
(`b`) in `S b = a` expression. To make de assignment, you have to 
cast a to a non-constant expression:


S b = cast(S)a;

Or make `b` as const:

const S b = a;

Or, better, use auto keyword:

auto b = a;


Re: Is there a cleaner way of doing this?

2017-08-07 Thread Diego via Digitalmars-d

On Monday, 7 August 2017 at 08:01:26 UTC, Shachar Shemesh wrote:
It is often desired to have a struct with an extra parameter. 
The common way to do this is like so:


struct S(T) {
T param;

void initialize(T param) {
this.param = param;
// Other stuff
}
}

The problem is what happens when the param is optional. The 
common way to do this is to set T to void. This results in the 
following code:


struct S(T) {
enum HasParam = !is(T == void);
static if( HasParam ) {
T param;
}

static if( HasParam ) {
void initialize(T param) {
this.param = param;
// Other stuff
}
} else {
void initialize() {
// Same other stuff as above!
}
}
}

This is both tedious and error prone. Is there a cleaner way of 
doing this?


Just as an unrealistic fantasy, if the following code was 
legal, the problem would be resolved on its own:

void func(void p) {
void param;

param = p;

return param;
}


Of course, that code has its own set of problems, and I'm not 
really suggesting that change.


Shachar


You can use type default initialization property:

struct S(T) {
T param;

void initialize(T param = T.init) {
this.param = param;
// Other stuff
}
}

S!int s;
s.initialize(42);  // works
s.initialize();  // also works; s.param == int.init == 0