Is there a cleaner way of doing this?
Diego via Digitalmars-d
digitalmars-d at puremagic.com
Mon Aug 7 05:08:24 PDT 2017
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
More information about the Digitalmars-d
mailing list