Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
}
like image 352
Torsten Robitzki Avatar asked Dec 15 '22 15:12

Torsten Robitzki


2 Answers

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
{
};
like image 103
Brian Bi Avatar answered Jan 12 '23 14:01

Brian Bi


There might be a more elegant way, but you could make foo a metafunction that refers to itself:

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

int main()
{
    typedef typename foo< 5 >::type t; // won't compile
}
like image 35
Jason R Avatar answered Jan 12 '23 13:01

Jason R