Gabriel
Gabriel

Reputation: 9442

Static Assert inside struct allowed?

I have several template settings struct, is it ok, to use static asserts in these structs?

template<typename T, int N, (and so on...)>
struct Settings{
  static const int n = N;
  STATIC_ASSERT(n == 5);
  typedef typename T GAGA;
}

Thanks for your responses!

Upvotes: 5

Views: 2758

Answers (3)

You would have to look at the STATIC_ASSERT macro definition to see what is exactly going on. A common implementation of STATIC_ASSERT that can be used there could be:

#define STATIC_ASSERT( x ) \
   typedef char static_assert_failed[ (x) ? 1 : -1 ]

Usually there is a bit more trickery to get the line number to be part of the typedef so that more than one STATIC_ASSERT can be used in the same context, but you can see that this is allowed as it will expand to valid code in the struct definition:

template<typename T, int N, (and so on...)>
struct Settings{
  static const int n = N;
  typedef char static_assert_failed[ (n == 5) ? 1 : -1 ];
  typedef typename T GAGA;
}

Upvotes: 1

Ajay
Ajay

Reputation: 18431

template<typename T, int N>
struct Settings
{  
STATIC_ASSERT(N == 5);  
typedef typename T GAGA;
};

I dont see a valid reason to use n.

Upvotes: 0

jcoder
jcoder

Reputation: 30035

I don't know what your STATIC_ASSERT is but if you write it using c++11 style static_assert then this works fine and seems like a perfectly good use for static assert. (Well, perhaps not checking it's 5 but checking template parameters are suitable for instantating)

template<typename T, int N>
struct Settings {   
  static const int n = N;   
  static_assert(n == 5, "Error");   
  typedef typename T GAGA; 
};

Upvotes: 5

Related Questions