digitalmars.D.learn - static assert
a few questions, 1| the doc on the website is not 100% clear for me. Is it possible to have an optional const char[] argument in a static assert? 2| what am I doing wrong in the code below? Why doesn't the static assert fire? (remark that when putting the static assert in a separate mixin I can get it to work) roel ====================================================================== template itoa(int n) { static if (n<0) const char[] itoa = "-" ~ itoa!(-n); else static if (n<10) const char[] itoa = "0123456789"[n..n+1]; else const char[] itoa = itoa!(n/10) ~ "0123456789"[n%10]; } template Factor(int n:0) { const int Factor = 1; } template Factor(int n) { pragma(msg, itoa!(n)); static assert(n>0); const int Factor = n * Factor!(n-1); } import std.stdio; void main() { writefln(Factor!(-5)); }
Oct 21 2006
rm wrote:a few questions, 1| the doc on the website is not 100% clear for me. Is it possible to have an optional const char[] argument in a static assert? 2| what am I doing wrong in the code below? Why doesn't the static assert fire? (remark that when putting the static assert in a separate mixin I can get it to work) roel ======================================================================(...) The problem is that the order of evaluation of statements within a template instantiation is not defined. In that case, the recursion was evaluating before the static assert. One possible way to solve it: template itoa(int n) { static if (n<0) const char[] itoa = "-" ~ itoa!(-n); else static if (n<10) const char[] itoa = "0123456789"[n..n+1]; else const char[] itoa = itoa!(n/10) ~ "0123456789"[n%10]; } template Factor(int n:0) { const int Factor = 1; } template next(int i) { static assert(i>0, "the optional const char[] argument ;) oh and by the way i = " ~ itoa!(i)); const int next = i-1; } template Factor(int n) { pragma(msg, itoa!(n)); const int Factor = n * Factor!(next!(n)); } import std.stdio; void main() { writefln(Factor!(-5)); } -- Tomasz Stachowiak
Oct 21 2006
thx, so that the code beneath works (with the mixin), is (bad) luck? roel // ----------------------------------- template Factor(int n:0) { const int Factor = 1; } template Factor(int n) { pragma(msg, itoa!(n)); // static assert(n>0); mixin AssertWithMsg!(n>0,"only positive integers allowed"); const int Factor = n * Factor!(n-1); } template AssertWithMsg(bool cond:false, char[] s) { pragma(msg,s); static assert(false); } template AssertWithMsg(bool cond:true, char[] s) { } import std.stdio; void main() { writefln(Factor!(-5)); }
Oct 21 2006