Search code examples
c++c++11assertstatic-assert

static_assert of class template parameter


Can I do the following to check that class template integer parameter is even:

template<int N>
struct S
{
     static_assert( N % 2 == 0, "fail" );
};

This compiles with gcc 4.8.3, but I am not sure if this code does not violate C++11 standard, and if it is going to work with other standard-compliant compilers.


Solution

  • The only real requirement of using static_assert is that the expression used must be a constant expression (i.e. the value must be determinable at compile-time), so you will run into an issue if you attempt to use a value that is not known until run-time.

    So as long as the values you use are compile-time constants you should be fine.