将用户定义的属性添加到D中的所有类型

bjz*_*bjz 2 alias types casting d

我正在使用Derelict来完成我的OpenGL工作,而且我已经厌倦了不得不cast(GLvoid*) Vec3.sizeof像glVertexAttribPointer这样的功能.所以我以为我会做一个功能,glsizeof

import std.stdio;

alias void GLvoid;

struct Vec3 {
    float x, y, z;
}

GLvoid* glsizeof(T)(T t) {
    return cast(GLvoid*) t.sizeof;
}

void main() {

    Vec3 vec = { x: 2.5, y: 4.8, z: 3.2 };

    writeln(cast(GLvoid*) vec.sizeof);  // prints 'C'
    writeln(cast(GLvoid*) Vec3.sizeof); // prints 'C'
    writeln(cast(GLvoid*) int.sizeof);  // prints '4'


    // Now to try using glsizeof :)

    GLvoid* size_vec  = vec.glsizeof;   // call glsizeof using a uniform function call
    GLvoid* size_vec3 = Vec3.glsizeof;
    GLvoid* size_int  = int.glsizeof;

    writeln(size_vec);  // should print 'C'
    writeln(size_vec3); // should print 'C'
    writeln(size_int);  // should print '4'
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

test.d(25): Error: no property 'glsizeof' for type 'Vec3'
test.d(26): Error: no property 'glsizeof' for type 'int'
Run Code Online (Sandbox Code Playgroud)

有没有办法向类型添加属性?或者我可以用另一种方式做到这一点,例如使用别名?或者我正在尝试做什么不可能?

这是关于DPaste 的代码.

编辑:在我的预期输出上添加了更多细节.

Jon*_*vis 7

简答:不.您不能将类型传递给函数,只能传递模板,如果要向某些属性添加属性,则需要声明属性函数.

但是,由于您可以将类型传递给模板,因此可以声明

template glsizeof(T)
{
    enum glsizeof = cast(GLvoid*)T.sizeof;
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以做到

GLvoid* size_vec3 = glsizeof!Vec3;
GLvoid* size_int  = glsizeof!int;
Run Code Online (Sandbox Code Playgroud)

所以,只要你不习惯使用语法Type.glsizeof,你就有了解决方案.如果你对它挑剔,那么对不起,但你运气不好.您可以glsizeof为您定义的每种类型定义.例如

struct S
{
    enum glsizeof = cast(GLvoid*)S.sizeof;
}
Run Code Online (Sandbox Code Playgroud)

但这不适用于您未定义的任何类型,包括内置类型.