Templated Enums?
Era Scarecrow
rtcvb32 at yahoo.com
Wed Jun 6 12:01:21 PDT 2012
I've come across an interesting problem. You can template quite
a few items, but not enums? Some thoughts from the experts would
likely be nice. Consider...
enum(T) X{ //syntax error
bitsPerT = T.sizeof * 8,
//further calculation types can follow
}
assert(X!(byte).bitsPerT == 8);
The compile complains outright you can't do this, but enclosing
it in a struct makes that problem go away with the same results.
struct(T) X {
enum {
bitsPerT = T.sizeof * 8,
}
}
assert(X!(byte).bitsPerT == 8); //compiles and works
Now obviously X!(byte).bitsPerT is a mouthful, and although alias
can condense the code, using different inner members require
unique names, With does a simpler job in a smaller more compact
scope.
alias X!(byte) bitsPerByte; //unique name unless small scope
assert(bitsPerByte == 8);
with(X!(int)) {
assert(bitsPerT == 32);
}
Unfortunately properties (static functions) don't work with this.
struct(T) X {
@property static T plusOne(T i) {return i + 1;}
}
with(X!int) {
int x;
writeln(x.plusOne); //error: plusOne function/template not
defined...
writeln(plusOne(x)); //works
}
More information about the Digitalmars-d-learn
mailing list