Templated Enums?

Ali Çehreli acehreli at yahoo.com
Wed Jun 6 17:53:12 PDT 2012


On 06/06/2012 05:33 PM, Era Scarecrow wrote:
 > On Wednesday, 6 June 2012 at 20:52:14 UTC, bearophile wrote:
 >> That seems correct, this works:
 >>
 >> template Foo(T) {
 >> enum Foo {
 >> bitsPerT = T.sizeof * 8,
 >> }
 >> }
 >> void main() {
 >> pragma(msg, Foo!int.bitsPerT);
 >> }
 >>
 >>
 >> So if template Foo(T){enum Foo{}} works, then I think it should also
 >> work the enum Foo(T){} syntax.
 >>
 >> So far I don't think I have had to use templated enums, but if other
 >> people have such need, than this thread and this post have enough
 >> material for a little enhancement request.
 >
 > Well if it was only 1-2 value I wouldn't probably have bothered. However
 > when there are several flags enums and values that are calculated based
 > on eachother and used together; I wouldn't want to write enums manually
 > for each type.
 >
 > Seems I'm being thrown now into the deep end of templates and
 > constraints and traits and trying to fully understand it enough to use
 > it all. What an exciting time to be alive :)

As far as I understand, this is all you need:

template bitsPer(T)
{
     static if (is (T ClassType == class)) {
         enum bitsPer = __traits(classInstanceSize, ClassType) * 8;

     } else {
         enum bitsPer = T.sizeof * 8;
     }
}

class C
{
     int[10] a;
}

void main()
{
     static assert(bitsPer!byte == 8);
     static assert(bitsPer!int == 32);
     static assert(bitsPer!C == 448);
}

Other specializations of bitsPer may be needed.

Ali

-- 
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html



More information about the Digitalmars-d-learn mailing list