pass a struct by value/ref and size of the struct

Namespace via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Apr 2 05:39:25 PDT 2016


> auto ref add(V)(auto ref V v1, auto ref V v2);
>
> // default this(this)
> Vec3f vec1;
>
> // accepts both lvalues and rvalues
> auto res = add(vec1, Vec3f(1, 2, 3.14));

auto ref produces template bloat. That is no real solution for 
the rvalue ref problem. But there is (more or less) a workaround:

----
import std.stdio;
import std.algorithm : sum;

struct Matrix4x4 {
	private Matrix4x4* _ref;
	
	float[16] values = [
		1, 0, 0, 0,
		0, 1, 0, 0,
		0, 0, 1, 0,
		0, 0, 0, 1
	];
	
	ref Matrix4x4 byRef() {
		_ref = &this;
		
		return *_ref;
	}
	
	double sum() const {
		return this.values[].sum;	
	}
}

void foo(ref const Matrix4x4 mat) {
	writeln("foo: ", mat.sum);
}

void main() {
	Matrix4x4 m;
	foo(m);
	foo(Matrix4x4().byRef);
}
----


More information about the Digitalmars-d-learn mailing list