Implementing a C-style sizeof() function in D

68 views Asked by At

I'd like to implement a C-style sizeof() function in D. (I know about the .sizeof thing, but it's to help in porting a lot of C (C99).)

I want it to be able to run at compile-time, obviously and take a type or an expression as an argument. Ideally, I'd like it to have the same syntax as C, if at all possible, rather than use the distinctive template invocation syntax, as that would greatly increase its utility. Is this at all possible?

1

There are 1 answers

10
greenify On

If I understand you correctly, you want a behavior similar to the size function below? size2 would be a runtime function, which of course is a bit pointless in D. However you can still get the value from size2 at CT with enum val = size2(2 + 2);. Does this help you?

template size(T)
{
    enum size = T.sizeof;
}

// for expressions
template size(alias T)
{
    enum size = T.sizeof;
}

auto size2(T)(T x)
{
    return T.sizeof;
}

void main(string[] args)
{
    import std.stdio : writeln;

    writeln(size!int); // 4
    writeln(size!long); // 8
    writeln(size!(1 + 1)); // 4


    writeln(size2(2));  // 4
    writeln(size2(2L)); // 8
    writeln(size2(2 + 2)); // 4
}