July 13, 2015 Re: Delayed const variable initialization | ||||
---|---|---|---|---|
| ||||
Posted in reply to Yuxuan Shui Attachments: | On Mon, 13 Jul 2015 09:08:13 +0000, Yuxuan Shui wrote: > No! What I want to do is to assign to 'const' only ONCE. So it is basically an initialization. it is forbidden to do assigning to `const`. and D has *no* "uninitialized variable" thingy, even `x = void` is initialization too (in technical sense). so you want c++-like const, which `Rebindable` does. > What I really want is to detach initialization from definition. you can't. it's by design. |
July 13, 2015 Re: Delayed const variable initialization | ||||
---|---|---|---|---|
| ||||
Posted in reply to Yuxuan Shui | On 7/13/15 3:11 AM, Yuxuan Shui wrote:
> How can I do something like this?
>
> const(A) x;
> if (condition) {
> x = func1();
> } else {
> x = func2();
> }
>
> This is a valid use case, and to make this work I'll have to use
> Rebindable, which is really inconvenient.
auto xvalue() {
if(condition) {
return func1();
} else {
return func2();
}
}
const(A) x = xvalue();
Essentially you can assign on initialization, so you have to encapsulate the initialization into one call. D allows nested functions quite easily, so you can do this.
You can also do a temporary lambda that you call immediately, but I'm not 100% sure of the syntax. Someone will chime in with the answer :)
-Steve
|
July 13, 2015 Re: Delayed const variable initialization | ||||
---|---|---|---|---|
| ||||
Posted in reply to Steven Schveighoffer | On Monday, 13 July 2015 at 14:41:36 UTC, Steven Schveighoffer wrote:
> You can also do a temporary lambda that you call immediately, but I'm not 100% sure of the syntax. Someone will chime in with the answer :)
>
> -Steve
Syntax is easy:
void main() {
bool condition;
const x = {
if(condition) {
return 1;
} else {
return 2;
}
}();
}
|
July 13, 2015 Re: Delayed const variable initialization | ||||
---|---|---|---|---|
| ||||
Posted in reply to Jesse Phillips | On Monday, 13 July 2015 at 17:18:53 UTC, Jesse Phillips wrote:
> On Monday, 13 July 2015 at 14:41:36 UTC, Steven Schveighoffer wrote:
>> You can also do a temporary lambda that you call immediately, but I'm not 100% sure of the syntax. Someone will chime in with the answer :)
>>
>> -Steve
>
> Syntax is easy:
>
> void main() {
> bool condition;
> const x = {
> if(condition) {
> return 1;
> } else {
> return 2;
> }
> }();
> }
This is pretty neat. Thanks!
|
Copyright © 1999-2021 by the D Language Foundation