Search code examples
c++templatesc++11type-traitsstatic-assert

type_traits for std Container?


I looked through the listing of std::type_traits but I didn't see anything in there pertaining to an std container.

I'm looking to validate that a std container was passed into a template type at compile time.

template < typename T >
void foo( T bar )
{
    static_assert( is_std_container??? );
}

Solution

  • It does not exist.

    You can create your own trait if you know the set of container types that should be supported :

    template<class T>
    struct is_container
    {
        static const bool value = false;
    };
    
    template<>
    template<class T, class Alloc>
    struct is_container<std::vector<T, Alloc>>
    {
        static const bool value = true; 
    };
    
    // ... same specializations for other containers.
    

    And you use it like other traits:

    cout << is_container<std::vector<int>>::value << endl;
    cout << is_container<int>::value << endl;
    

    See it here.

    Note that usually you should pass iterators to your functions, not containers. So you keep your code container-independent and much more generic.