'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 1:[1]

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 ) { ... }

Solution 2:[2]

How about this:

template <class T2>
struct is_std_vector { static const bool value=false; };

template <class T2>
struct is_std_vector<std::vector<T2> > { static const bool value=true; };

Use together with enable_if!

Solution 3:[3]

Why do you even want to use a template for that? Can't you just write a plain function?

Anyhow, it's possible:

template<class T
  ,class=typename std::enable_if<(
    std::is_same<T,std::vector<int>>::value
  )>::type
>
void foo(T const& vec)

(this is C++11: default template arguments for function templates + type_traits + >> not being a shift operator)

Edit: I just realized that T2 in your question is probably not some fixed type but a placeholder to allow many kinds of vectors. In that case, I recommend accepting Luc's answer.

Viele Grüße nach Österreich! :-)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Luc Touraille
Solution 2 Alexis Wilke
Solution 3