FireAphis
FireAphis

Reputation: 6790

How to implement is_stl_vector

I want to specialize a template for STL's vector template arguments. Something like this:

// (1)
template <typename T>
class A
{
    ...
};

// (2)
template <>
class A<std::vector<> >
{
    ...
};

I don't care what is the type of the vector element. I would like to use it as follows:

A<int> a1; // Will use the general specialization
A<std::vector<int> > a2; // Will use the second specialization

In general I've been trying to define something similar to boost's type traits. Something like

template <class T> 
struct is_stl_vector 
{
    // Will be true if T is a vector, false otherwise
    static const bool value = ...; 
};

I cannot use template template (I think so) because it should compile for non-template types too. Is it possible at all?

Upvotes: 4

Views: 267

Answers (2)

Grizzly
Grizzly

Reputation: 20201

You can simply specialize like this:

// (2)
template <typename T, typename Alloc>
struct A<std::vector<T, Alloc> >
{...};

Upvotes: 7

jpalecek
jpalecek

Reputation: 47770

The specialization goes like this:

// (2)
template <class T, class U>
class A<std::vector<T, U> >
{
    ...
};

Note that it is not guaranteed to work (and there si no other way that's guaranteed to work), because the template parameter count of std::vector may vary across implementations. In C++0x, this should be solvable using parameter packs.

Upvotes: 6

Related Questions