[C ++ compile time statements]: Is it possible to execute a compilation error if any condition is not met?

I wrote a function:

template<int N> void tryHarder() { for(int i = 0; i < N; i++) { tryOnce(); } } 

but I want it to compile if N is between 0 and 10. Can I do this? How?

+7
source share
4 answers

You can do this using the static_assert declaration :

 template<int N> void tryHarder() { static_assert(N >= 0 && N <= 10, "N out of bounds!"); for(int i = 0; i < N; i++) { tryOnce(); } } 

This feature is only available with C ++ 11. If you are stuck with C ++ 03, see Enhance static confirmation macro .

This whole idea is good error messages. If you do not care about them or cannot increase the level of support, you can do something as follows:

 template<bool B> struct assert_impl { static const int value = 1; }; template<> struct assert_impl<false> { static const int value = -1; }; template<bool B> struct assert { // this will attempt to declare an array of negative // size if template parameter evaluates to false static char arr[assert_impl<B>::value]; }; template<int N> void tryHarder() { assert< N <= 10 >(); } int main() { tryHarder<5>(); // fine tryHarder<15>(); // error, size of array is negative } 
+14
source

For pre C ++ 11 compilers, you can implement a template parameter constraint for a non-type N.

For a description of how to do this, see http://stroustrup.com/bs_faq2.html#constraints

+1
source

Combined with the answers so far given, the lower bound can also be covered using unsigned int as the template type. Negative values, if applicable, will be converted to unsigned values โ€‹โ€‹high enough to be covered using static_assert or C ++ 11 preliminary solution.

unsigned int additionally already gives a semantically hint that negative values โ€‹โ€‹should not be applied to this template, so it (maybe) should be preferred in a particular case ...

0
source
 #if !defined(__cplusplus) #error C++ compiler required. #endif 

This is just an example.

Here is the source link: http://msdn.microsoft.com/en-us/library/c8tk0xsk(v=vs.71).aspx

All I say is that you can use #error as well

This is a directive.

Edit @Pratik Chowdhruy: I agree with Paul R. This does not directly answer the question. Sorry for the community

-2
source

All Articles