www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to manage function's parameter storage class?

reply Sobaya <sobaya007 gmail.com> writes:
I'm using opDispatch for wrapping a function like below.

```
import std.stdio;

void func(ref int x, int y) {
     x++;
}

struct B {
     // wraps 'func'. I want to implement this function.
     template opDispatch(string fn) {
         void opDispatch(Args...)(Args args) {
             mixin(fn~"(args);"); // func(args);
         }
     }
}

void main() {
     {
         // This is good behavior.
         int x = 3;
         func(x, 1);
         writeln(x);   // prints '4'
     }
     {
         // This is bad behavior.
         B b;
         int x = 3;
         b.func(x, 1);
         writeln(x);   // prints '3' because x is copied when 
passed to opDispatch.
     }

}
```

How can I wrap function whose arguments contain both ref and 
normal like 'func' ?
With normal 'Args', x is not increased because x is copied when 
passed to opDispatch.
If I write 'ref Args' in opDispatch's argument, it fails because 
second parameter is not rvalue.
Jan 20 2018
parent reply Simen =?UTF-8?B?S2rDpnLDpXM=?= <simen.kjaras gmail.com> writes:
On Saturday, 20 January 2018 at 14:31:59 UTC, Sobaya wrote:
 How can I wrap function whose arguments contain both ref and 
 normal like 'func' ?
 With normal 'Args', x is not increased because x is copied when 
 passed to opDispatch.
 If I write 'ref Args' in opDispatch's argument, it fails 
 because second parameter is not rvalue.
https://dlang.org/spec/function.html#auto-ref-functions Simply put, instead of 'ref' use 'auto ref'. -- Simen
Jan 20 2018
parent Sobaya <sobaya007 gmail.com> writes:
On Saturday, 20 January 2018 at 17:05:40 UTC, Simen Kjærås wrote:
 On Saturday, 20 January 2018 at 14:31:59 UTC, Sobaya wrote:
 How can I wrap function whose arguments contain both ref and 
 normal like 'func' ?
 With normal 'Args', x is not increased because x is copied 
 when passed to opDispatch.
 If I write 'ref Args' in opDispatch's argument, it fails 
 because second parameter is not rvalue.
https://dlang.org/spec/function.html#auto-ref-functions Simply put, instead of 'ref' use 'auto ref'. -- Simen
Oh... I missed it... Thanks! !
Jan 20 2018