C++ vs D: Default param values and struct to array casting

Andrew Edwards edwards.ac at gmail.com
Fri Sep 6 09:14:31 UTC 2019


C++ allows the for following:

struct Demo
{
	float a, b, c, d;
	Demo() { a = b = c = d = 0.0f; }
	Demo(float _a, float _b, float _c, float _d) {
		a = _a;
		b = _b;
		c = _c;
		d = _d;
	}
	float  operator[] (size_t i) const { return (&a)[i]; } //[3]
	float& operator[] (size_t i) { return (&a)[i]; } //[4]
}

void fun(float col[3])
{
	// do fun stuff
}

void moreFun(const Demo& d = Demo(0.1f, 0.3f, 7.5f, 1.5f)) // [1]
{
	// you guessed it... more fun stuff
}

int main(int argv, const char** argc)
{
	Demo inst = Demo(0.1f, 0.3f, 7.5f, 1.5f);
	fun((float*)&inst); // [2]
	moreFun();
	return 0;
}

I'm seeking some pointers on how to define these in D so that I 
can instantiate them in D while still linking to the associated 
C++ library or object file for the implementation. The main 
points of contention are at [1] and [2] because I have no idea 
how to accomplish these.  I assume that I can accomplish [3] and 
[4] with opIndex() and opIndexAssign(), however I'm not 
understanding the slicing of the memory address at the first 
member variable. I know that by indexing the memory address at 
the member variable we are able treat the struct as an array but 
i do not understand how to implement it in D.

I read the documentation at 
https://dlang.org/spec/cpp_interface.html and 
https://dlang.org/articles/cpptod.html but it was not clear "to 
me" how to overcome these issues.

Andrew


More information about the Digitalmars-d-learn mailing list