【问题标题】:STL container type as template parameterSTL 容器类型作为模板参数
【发布时间】:2013-01-21 11:32:48
【问题描述】:

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

#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;

最自然的方法是什么?比如说,你是否想以任何形式提及容器分配器的存在?

【问题讨论】:

  • 我建议你最好不要这样做。虽然 STL 容器在接口上相似,但它们必然相同。此外,使用一个容器的最有效方式不一定是使用另一个容器的最有效方式。我认为您不太可能成功地模板化您的存储而不会遇到困难。你为什么要这样做?你想达到什么目标?
  • 我想在访问元素的速度(允许向量)和插入速度(提供列表)之间做出选择。

标签: c++ c++11


【解决方案1】:

这样的?

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 中进行了测试,展示了如何处理分配器。

【讨论】:

  • @Dukales:看我的编辑。你的意思是什么替代方案?您的问题不包含任何猜测这一点的信息。
  • 所以在这种情况下我们只能使用(constructor) empty size front back push pop?但是&lt;algorithm&gt; 的呢?
  • 没有解决template&lt; ... &gt; struct C的参数列表膨胀的问题。
  • @Dukales: 主要使用迭代器,所以只要您使用兼容的迭代器,这应该没问题。正如 Jack Aidley 所说,他的评论是,STL 容器非常不兼容,但仍有可互换的空间。
  • @Dukales:请详细说明为什么需要template&lt; ... &gt; struct C。如果您提供的信息如此有限,我无法帮助您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-07
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-03
  • 1970-01-01
相关资源
最近更新 更多