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

Can static_assert check if a type is a vector?


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")

Solution

  • 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.