digitalmars.D - How to determine constness at compile time?
- Janice Caron (23/23) Nov 27 2007 I'm trying to write a template to determine the constness (or not) of
- Steven Schveighoffer (44/47) Nov 27 2007 import std.stdio;
- Janice Caron (6/6) Nov 27 2007 That is genius! Sheer genius! Thank you.
- Steven Schveighoffer (6/11) Nov 27 2007 I think it has something to do with the alias Y statement, because now
I'm trying to write a template to determine the constness (or not) of array members. The following seemed the obvious thing to do, but it doesn't work. Anyone know how to do it right? template constID(T) { static if(is(T:invariant(T)[])) { static const int constID = 2; } else static if(is(T:const(T)[])) { static const int constID = 1; } else { static const int constID = 0; } } void main() { writefln(constID!(string)); } This prints 0. I would have expected (hoped for) it to print 2.
Nov 27 2007
"Janice Caron" wroteI'm trying to write a template to determine the constness (or not) of array members. The following seemed the obvious thing to do, but it doesn't work. Anyone know how to do it right?import std.stdio; template realConstID(T) { static if(is(T X : X[])) alias X Y; else static if(is(T X : X*)) alias X Y; else alias T Y; static if(is(Y == invariant(Y))) { static const int constID = 2; } else static if(is(Y == const(Y))) { static const int constID = 1; } else { static const int constID = 0; } } template constID(T) { static const int constID = realConstID!(T).constID; } void main() { writefln(constID!(char[])); writefln(constID!(const(char)[])); writefln(constID!(invariant(char)[])); writefln(constID!(char*)); writefln(constID!(const(char)*)); writefln(constID!(invariant(char)*)); } outputs: 0 1 2 0 1 2 -Steve
Nov 27 2007
That is genius! Sheer genius! Thank you. I did ponder for a while why constID!() invoked realConstID!(), instead of doing it in a single template. So I did the experiment and found it wouldn't compile if you did it in a single template. I don't know why though! Anyway, cheers!
Nov 27 2007
"Janice Caron" wroteThat is genius! Sheer genius! Thank you.*blushes* :)I did ponder for a while why constID!() invoked realConstID!(), instead of doing it in a single template. So I did the experiment and found it wouldn't compile if you did it in a single template. I don't know why though!I think it has something to do with the alias Y statement, because now constID is not the only member of the template. I know you said this worked for you in the past, but maybe it was just luck that it worked :) -Steve
Nov 27 2007