允许在D中进行[i]和.xyz操作的快速向量结构?

0sc*_*car 5 struct d operator-overloading

我想在D中创建一个像这样工作的向量结构:

vec u, v;
vec w = [2,6,8];
v.x = 9; // Sets x
v[1] = w.y; // Sets y
u = v; // Should copy data
Run Code Online (Sandbox Code Playgroud)

后来我也想添加类似的东西u = v * u.但是上面的内容现在也可以.
这是我走了多远:

struct vec3f
{
    float[3] data;
    alias data this;
    @property
    {
        float x(float f) { return data[0] = f; }
        float y(float f) { return data[1] = f; }
        float z(float f) { return data[2] = f; }
        float x() { return data[0]; }
        float y() { return data[1]; }
        float z() { return data[2]; }
    }
    void opAssign(float[3] v)
    {
        data[0] = v[0];
        data[1] = v[1];
        data[2] = v[2];
    }
}
Run Code Online (Sandbox Code Playgroud)

现在这几乎使它像我想要的那样工作,但我觉得这是否"正确"是非常不确定的.opAssign()是否应该返回一些值?

我也想知道这是否真的如此快?我是否尝试过添加alias data[0] x;等等但这不起作用.有任何想法吗?或者这是"它是如何完成的"?也许编译器足够聪明,可以弄清楚功能或多或少的别名?

dsi*_*cha 5

Overall, this looks pretty reasonable. For the purpose of assignment chaining, opAssign should arguably return v. However, in practice this is often overlooked and might cause a performance hit (I don't know). Unlike in D1, you can return static arrays from functions in D2.

As far as performance, the best way to think of this is at the assembly level. Assuming inlining is enabled, x() will almost certainly be inlined. Static arrays are stored directly in the struct without an extra layer of indirection. The instruction return data[0]; will cause the compiler to generate code to read from an offset from the beginning of the struct. This offset will be known at compile time. Therefore, most likely calling x() will generate exactly the same assembly instructions as if x were actually a public member variable.

One other possibility, though, would be to use an anonymous union and struct:

struct vec3f
{
    union {
        float[3] vec;

        struct {
            float x;
            float y;
            float z;
        }
    }

    alias vec this;  // For assignment of a float[3].

}
Run Code Online (Sandbox Code Playgroud)

Note, though that alias this is fairly buggy right now, and you probably shouldn't use it yet unless you're willing to file some bug reports.