How to write a type trait `is_container` or `is_vector`?

Viewed 26039

Is it possible to write a type trait whose value is true for all common STL structures (e.g., vector, set, map, ...)?

To get started, I'd like to write a type trait that is true for a vector and false otherwise. I tried this, but it doesn't compile:

template<class T, typename Enable = void>
struct is_vector {
  static bool const value = false;
};

template<class T, class U>
struct is_vector<T, typename boost::enable_if<boost::is_same<T, std::vector<U> > >::type> {
  static bool const value = true;
};

The error message is template parameters not used in partial specialization: U.

11 Answers

Fast forward to 2018 and C++17, I was so daring to improve on @Frank answer

// clang++ prog.cc -Wall -Wextra -std=c++17

 #include <iostream>
 #include <vector>

 namespace dbj {
    template<class T>
      struct is_vector {
        using type = T ;
        constexpr static bool value = false;
   };

   template<class T>
      struct is_vector<std::vector<T>> {
        using type = std::vector<T> ;
        constexpr  static bool value = true;
   };

  // and the two "olbigatory" aliases
  template< typename T>
     inline constexpr bool is_vector_v = is_vector<T>::value ;

 template< typename T>
    using is_vector_t = typename is_vector<T>::type ;

 } // dbj

   int main()
{
   using namespace dbj;
     std::cout << std::boolalpha;
     std::cout << is_vector_v<std::vector<int>> << std::endl ;
     std::cout << is_vector_v<int> << std::endl ;
}   /*  Created 2018 by dbj@dbj.org  */

The "proof the pudding". There are better ways to do this, but this works for std::vector.

We can also use concepts. I compiled this with GCC 10.1 flag -std=c++20.


#include<concepts>

template<typename T>
concept is_container = requires (T a)
{ 
    a.begin(); 
    // Uncomment both lines for vectors only
    // a.data(); // arrays and vectors
    // a.reserve(1); // narrowed down to vectors
    
};

Related