c++ - How do I validate template parameters in compile time when a templated class contains no usable member functions? -


i have following templated struct:

template<int degree> struct cpoweroften { enum { value = 10 * cpoweroften<degree - 1>::value }; };  template<> struct cpoweroften<0> {     enum { value = 1 }; }; 

which used this:

const int numberofdecimaldigits = 5; const int maxrepresentablevalue = cpoweroften<numberofdecimaldigits>::value - 1; // can use both constants safely - they're surely in sync 

now template requires degree non-negative. i'd enforce compile-time assert that.

how do that? tried add destructor cpoweroften:

~cpoweroften() {     compiletimeassert( degree >= 0 );  } 

but since not called directly visual c++ 9 decides not instantiate , compile-time assert statement not evaluated @ all.

how enforce compile-time check degree being non-negative?

template<bool> struct staticcheck; template<> struct staticcheck<true> {};  template<int degree>  struct cpoweroften : staticcheck<(degree > 0)> {      enum { value = 10 * cpoweroften<degree - 1>::value };  };   template<>  struct cpoweroften<0> {      enum { value = 1 };  };  

edit: without infinite recursion.

// struct template<bool, int> struct cpoweroftenhelp;  // positive case     template<int degree>  struct cpoweroftenhelp<true, degree> {      enum { value = 10 * cpoweroftenhelp<true, degree - 1>::value };  };   template<>  struct cpoweroftenhelp<true, 0> {      enum { value = 1 };  };   // negative case template<int degree>  struct cpoweroftenhelp<false, degree> {}  // main struct template<int degree>  struct cpoweroften : cpoweroftenhelp<(degree >= 0), degree> {}; 

Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -