Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type_traits for std Container? [duplicate]

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??? );
}
like image 673
Jonathan Mee Avatar asked Sep 24 '26 21:09

Jonathan Mee


1 Answers

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.

like image 132
quantdev Avatar answered Sep 27 '26 10:09

quantdev