How to make a generic function to take a class or struct by reference?
JN
666total at wp.pl
Sun Mar 27 16:27:44 UTC 2022
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()
{
*getX(this) = 5;
}
}
class Bar
{
int x;
void doStuff()
{
*getX(this) = 5;
}
}
int* getX(T)(ref T t)
{
return &t.x;
}
int* getX(T)(T t)
{
return &t.x;
}
void main()
{
Foo foo;
Bar bar = new Bar();
foo.doStuff();
bar.doStuff();
assert(foo.x == 5);
assert(bar.x == 5);
}
```
More information about the Digitalmars-d-learn
mailing list