Search code examples
c++templatestemplate-specializationtemplate-meta-programming

Enable template only for some std::vector<T2> type


I would to make a template match only for T=std::vector<T2> arguments (T2 is an arbitrary type). I can use boost::enable_if in template arguments. How do I test whether a type T is a std::vector?

I could include T::iterator in my template so that non-container types would lead to substitution failure and would not be considered (SFINAE). This way though, any containers which define T::iterator would match, not only std::vector<T2>.


Solution

  • You probably don't need enable_if, a simple partial specialization should be enough:

    template <typename T>
    struct Type { ... };
    
    // partial specialization for std::vector
    template <typename T>
    struct Type< std::vector< T > > { ... };
    

    If you are dealing with a function template, you can simply provide an overload:

    template <typename T>
    void foo( const T & t ) { ... }
    
    // overload for std::vector
    template <typename T>
    void foo( const std::vector< T > & vec ) { ... }