Re: How to make a generic function to take a class or struct by reference?

2022-03-28 Thread Ali Çehreli via Digitalmars-d-learn
On 3/27/22 22:32, vit wrote: > int* getX(T)(return auto ref T t) > if(is(T == class) || (is(T == struct) && __traits(isRef, t))){ > return &t.x; > } I also think 'return' parameter is needed but I could not come up with an example where that 'return' provides any more safety. Compiler alr

Re: How to make a generic function to take a class or struct by reference?

2022-03-28 Thread Ali Çehreli via Digitalmars-d-learn
On 3/27/22 09:27, JN wrote: > I would like to have only one definition of getX if possible, because > they both are doing the same thing. I can't remove the ref one, because > without a ref it will pass the struct as a temporary and compiler won't > like that. Combining all responses, the code at

Re: How to make a generic function to take a class or struct by reference?

2022-03-27 Thread vit via Digitalmars-d-learn
On Sunday, 27 March 2022 at 16:27:44 UTC, JN wrote: I would like to have only one definition of getX if possible, because they both are doing the same thing. I can't remove the ref one, because without a ref it will pass the struct as a temporary and compiler won't like that. ```d import std.

Re: How to make a generic function to take a class or struct by reference?

2022-03-27 Thread Steven Schveighoffer via Digitalmars-d-learn
On 3/27/22 12:27 PM, JN wrote: int* getX(T)(T t) {     return &t.x; } Remove this one. It's a bad idea. It probably won't compile, but if it does, you will be using corrupted memory. -Steve

Re: How to make a generic function to take a class or struct by reference?

2022-03-27 Thread drug via Digitalmars-d-learn
Auto ref? ```D int* getX(T)(auto ref T t) { ... ```

How to make a generic function to take a class or struct by reference?

2022-03-27 Thread JN via Digitalmars-d-learn
I would like to have only one definition of getX if possible, because they both are doing the same thing. I can't remove the ref one, because without a ref it will pass the struct as a temporary and compiler won't like that. ```d import std.stdio; struct Foo { int x; void doStuff()