STL容器类型作为模板参数

STL container type as template parameter

本文关键字:参数 类型 STL      更新时间:2023-10-16

我想创建一个泛型类模板,它在内部使用一个特定的容器来确定不同的类型。像这样:

#include <vector>
#include <list>
template< typename F, template< class ... > class container_type = std::vector >
struct C
{
    C();
    template< typename U >
    C(container_type< U >);
    C(container_type< F >);
    C(container_type< int >);
    container_type< double > param;
};
C< unsigned, std::list > c;

最自然的方法是什么?比方说,您是否希望以任何形式提到容器分配器的存在?

像这样?

template< typename F, template<class T, class = std::allocator<T> > class container_type = std::vector >
struct C
{
    C() {}
    template< typename U >
    C(container_type< U >) {}
    C(container_type< F >) {}
    C(container_type< int >) {}
    container_type< double > param;
};
C< unsigned, std::list > c;
编辑:

std::queue使用了类似但更简单的方法,它由内部使用的容器类型参数化。希望这证明了这种方法是很自然的。上面的示例在vc++ 10中进行了测试,并展示了如何处理分配器。