Search code examples
c++static-assert

Force static_assert to fire during type instantiating


how could I force the static_assert in this given class:

template < int I >
struct foo
{
    static_assert( I < 5 ,"I must be smaller than 5!" );
};

to fire when I instantiate the template no when I instantiate the resulting type:

int main()
{
    typedef foo< 5 > t; // compiles
    t tt; // will not compile 
}

Solution

  • One suggestion

    template <int I>
    struct foo_guard {
      static_assert(I < 5, "I must be smaller than 5!");
      typedef void type;
    };
    template < int I, typename = typename foo_guard<I>::type>
    struct foo
    {
    };