TITLE: enforcing some constraints at compile-time (Newsgroups: comp.lang.c++.moderated, 3 May 99) GREIF: "Gabor Greif" > template > struct Reg > { > enum { checkNUM_0_7 = 1 / (NUM >= 0 && NUM <= 7) }; > // members, used for state and behaviour > // ... > }; > > This will lead to a division by 0 error at compile time, with the error > location hopefully pointing at the definition of checkNUM_0_7! PODOLSKY: Michael Podolsky Well, the last days i had a same problems. As for devision by 0, some compilers may not catch this as error in const expression (for instance, Borland). Here is a way i do the stuff: [ I had to modify the code below. I think the author left out some of it. -adc ] template class Check; class Check<2+2==5> {}; class Check<2+2==4>{enum{OK};}; // I wanted only 1 to be true logical value enum{AmIRight=Check<( sizeof(short)==2 ) >::OK}; // Want short to be 2 bytes enum{AmIRightMore=Check<( 6*6==49 ) >::OK}; // there were time I studied // mathematics in university !!! ;-) Or for class parameter: template class EnabledMyClass; class EnabledMyClass{}; class EnabledMyClass{}; class EnabledMyClass{}; template class MyClass // Generic type { enum {dummy=sizeof(EnabledMyClass); }; // yet with limited set of arguments ... // Generic Implementation }; ------------------------------------------------------------------------ (Newsgroups: comp.lang.c++.moderated, 29 Apr 99) MITCHELL: Ian Mitchell > template > class CompileTimeAssert > { > public: > CompileTimeAssert(){ int *dummy( int(!Status) ); > }; NARAN: Siemel Naran Fine. But the compiler may instantiate the constructor of the template class at link time rather than at compile time, in which case you don't get the error message till much later. That is, when the compiler parses this statement > CompileTimeAssert test_true; it instantiates the class CompileTimeAssert with Status==true in order to determine the sizeof(test_true), and whether the constructor and destructor are accessible. But there's no need to instantiate CompileTimeAssert::CompileTimeAssert() at this point. But on many compilers, this constructor will be instantiated here and now because it is inline. In any case, here is an alternative. template class CompileTimeAssert { typedef char dummy[Status]; public: CompileTimeAssert(){} }; MITCHELL: > // Generates cryptic error message > CompileTimeAssert< (sizeof(int)==3) > test_size; NARAN: Yes, the cryptic error messages are a pain.