Xander Tulip Xander Tulip - 3 months ago 17
C++ Question

Determine if a type is an STL container at compile time

I would like to write a template that will determine if a type is an stl container at compile time.

I've got the following bit of code:

struct is_cont{};
struct not_cont{};

template <typename T>
struct is_cont { typedef not_cont result_t; };

but I'm not sure how to create the necessary specializations for
std::vector<T,Alloc>, deque<T,Alloc>, set<T,Alloc,Comp>


First, you define your primary template, which will have a member which is false in the default case:

template <typename T>
struct is_cont {
  static const bool value = false;

Then you will define partial specializations for your container types which have a value of true instead:

template <typename T,typename Alloc>
struct is_cont<std::vector<T,Alloc> > {
  static const bool value = true;

Then for a type X that you want to check, use it like

if (is_cont<X>::value) { ... }