How are extra copy constructor parameters used?

Tejas notrealemail at gmail.com
Thu Dec 30 05:03:05 UTC 2021


On Thursday, 30 December 2021 at 04:42:06 UTC, Tejas wrote:
> On Thursday, 30 December 2021 at 01:04:10 UTC, Ali Çehreli 
> wrote:
>> The second item in the documentation mentions "any number of 
>> default parameters" when describing copy constructor syntax:
>>
>>   https://dlang.org/spec/struct.html#struct-copy-constructor
>>
>> 1) I can't figure out how to use those extra parameters. For 
>> example, I can't find a special function name to call 
>> explicitly:
>>
>>   S.__cctor(a, 42);  // No go
>>
>
>
> Behold the pathetic hack!
> ```d
> import std.stdio:writeln;
>
> struct A
> {
>     this(ref return scope A rhs) inout {}                       
>  // copy constructor
>     this(ref A rhs, int b = 7) inout {        					 // copy 
> constructor with default parameter
>         if (b != 7) {
>             rhs.b = b;//yes, modify the parameter, not the this 
> object :(
>             rhs.a = rhs.a;
>         }        	
>         else
>             foreach (i, ref field; rhs.tupleof)
>         		field = this.tupleof[i] ;
>
>
>     }
>     this(this) @disable;
>     int a=4;
>     int b=3;
> }
>
> void main()
> {
>     A a = A();
>     A b = void;
>     a.__ctor(b, 9); // because writing A b = A(a, 9); like a 
> sane human is giving errors D:
>     writeln(b.b);
> }
> ```
>
> Replacing `a.__ctor(b, 9);` with `A b = A(a, 9);` is yielding:
>
> ```d
> onlineapp.d(26): Error: cannot implicitly convert expression 
> `a` of type `A` to `int`
> ```

Ehh no need to get overly dramatic, I could've done 
`b.__ctor(a,9)` in order to prevent mutation via the parameter

```d
import std.stdio:writeln;

struct A
{
     this(ref return scope A rhs) inout {}                        
// copy constructor
     this(ref return scope const A rhs, int b = 7) inout {        
					 // copy constructor with default parameter
         if (b != 7) {
             this.b = b;
             this.a = rhs.a;
         }        	
         else
             foreach (i, ref inout field; rhs.tupleof)
         		this.tupleof[i] = field;


     }
     this(this) @disable;
     int a=4;
     int b=3;
}

void main()
{
     A a = A();
     A b = void;
     b.__ctor(a, 9);
     //b = A(a,9); //this still doesn't work :(
     writeln(b.b);
     writeln(b);
}
```



More information about the Digitalmars-d-learn mailing list