如何实现is_stl_vector

Fir*_*his 4 c++ templates boost

我想专门为STL的矢量模板参数设计一个模板.像这样的东西:

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

// (2)
template <>
class A<std::vector<> >
{
    ...
};
Run Code Online (Sandbox Code Playgroud)

我不在乎vector元素的类型是什么.我想用它如下:

A<int> a1; // Will use the general specialization
A<std::vector<int> > a2; // Will use the second specialization
Run Code Online (Sandbox Code Playgroud)

一般来说,我一直试图定义类似于boost类型特征的东西.就像是

template <class T> 
struct is_stl_vector 
{
    // Will be true if T is a vector, false otherwise
    static const bool value = ...; 
};
Run Code Online (Sandbox Code Playgroud)

我不能使用模板模板(我认为是这样),因为它也应该为非模板类​​型编译.有可能吗?

Gri*_*zly 7

你可以像这样专门化:

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

  • 你会获得+1,除非它不是那么简单.见jpalecek的回答. (2认同)

jpa*_*cek 6

专业化是这样的:

// (2)
template <class T, class U>
class A<std::vector<T, U> >
{
    ...
};
Run Code Online (Sandbox Code Playgroud)

请注意,它不能保证工作(并且没有其他方法可以保证工作),因为模板参数计数std::vector可能因实现而异.在C++ 0x中,这应该可以使用参数包解决.

  • 我认为这个答案不正确(最后一部分).请参阅http://stackoverflow.com/questions/1469743/standard-library-containers-with-additional-optional-template-parameters (3认同)