Can static_assert check if a type is a vector?

小太郎 picture 小太郎 · Aug 5, 2011 · Viewed 7.7k times · Source

Can static_assert check if a type is a vector? IE, an int would raise the assertion, whereas a vector<int> would not.
I'm thinking of something along the lines of:

static_assert(decltype(T) == std::vector, "Some error")

Answer

Arvid picture Arvid · Aug 5, 2011

Yes. Consider the following meta function:

#include <stdio.h>
#include <vector>

template <class N>
struct is_vector { static const int value = 0; };

template <class N, class A>
struct is_vector<std::vector<N, A> > { static const int value = 1; };

int main()
{
   printf("is_vector<int>: %d\n", is_vector<int>::value);
   printf("is_vector<vector<int> >: %d\n", is_vector<std::vector<int> >::value);
}

Simply use that as your expression in static_assert.