|
From: Jerzie.Klenchier on 30 Mar 2008 18:43 Hello all, I have the following piece of code: template<int i, int j, int k> void foo() { // rule: i >= j // static_assert(i >= j) // static_assert((i - j) >= 2 * k) } int main() { foo<1,2,3>(); return 0; } I was wondering how one would go about creating an assert that runs at compile time which would give an error message based on the assertion? I've seen static asserts for types but haven't seen any for value templates - any ideas? Jerzie -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
From: Daniel Krügler on 31 Mar 2008 01:43 On 31 Mrz., 11:43, Jerzie.Klench...(a)gmail.com wrote: > template<int i, int j, int k> > void foo() > { > // rule: i >= j > // static_assert(i >= j) > // static_assert((i - j) >= 2 * k) > > } > > int main() > { > foo<1,2,3>(); > return 0; > > } > > I was wondering how one would go about creating an > assert that runs at compile time which would give > an error message based on the assertion? > > I've seen static asserts for types but haven't seen > any for value templates - any ideas? Mind to explain, what you mean with "static asserts for types"? IMO something like BOOST_STATIC_ASSERT should do what you want. In code parts, which cannot dependent on boost, I usually use a very simple static assert via a typedef of an array: template<int i, int j, int k> void foo() { // rule: i >= j typedef bool IGrEqJ[i >= j]; typedef bool Constr2[(i - j) >= 2 * k]; } Some compilers accept this (don't ask me which), even if the result was false. In those pathological cases this form always worked: typedef bool IGrEqJ[(i >= j) ? 1 : -1]; typedef bool Constr2[((i - j) >= 2 * k) ? 1 : -1]; HTH & Greetings from Bremen, Daniel Kr�gler -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
|
Pages: 1 Prev: I got a strange error message when using fstream! Next: Good books about STL and template |