【问题标题】:A template that contains std collection iterators包含 std 集合迭代器的模板
【发布时间】:2019-01-08 21:02:08
【问题描述】:

此模板能够存储特定类型的向量迭代器。

template<typename T>
struct foo
{
  typedef typename std::vector<T>::iterator it;

  std::vector<it> m_collection;
};

如何使模板更通用并支持其他标准集合迭代器(std::liststd::deque 等)?

【问题讨论】:

  • 您要解决的实际问题是什么?这听起来像XY problem

标签: c++ templates stl c++14 template-templates


【解决方案1】:

如何使模板更通用并支持其他标准集合迭代器(列表、双端队列等)?

您想将容器作为模板参数传递吗?

也就是说:您在寻找模板-模板参数吗?

template <template <typename...> class C, typename T>
struct foo
{
  typedef typename C<T>::iterator it;

  std::vector<it> m_collection;
};

如下使用

foo<std::vector, int>  fvi;
foo<std::set, long>    fsl;

或许

template <template <typename...> class C, typename ... Ts>
struct foo
{
  typedef typename C<Ts...>::iterator it;

  std::vector<it> m_collection;
};

所以你也可以将它用于地图?

foo<std::map, int, std::string>      fmis;
foo<std::unordered_map, long, char>  fulc;

很遗憾,此解决方案与需要非模板参数的std::array 不兼容。

或者也许您想通过特化传递类型并选择容器和包含类型?

template <typename>
struct foo;

template <template <typename...> class C, typename ... Ts>
struct foo<C<Ts...>>
{
  typedef typename C<Ts...>::iterator it;

  std::vector<it> m_collection;
};

所以你可以如下使用它

foo<std::vector<int>>                fvi;
foo<std::set<long>>                  fsl;
foo<std::map<int, std::string>>      fmis;
foo<std::unordered_map<long, char>>  fulc;

并为std::array添加一个专业化

template <template <typename, std::size_t> class A,
          typename T, std::size_t N>
struct foo<A<T, N>>
{
  typedef typename A<T, N>::iterator it;

  std::vector<it> m_collection;
};

或者,也许,只是

template <typename T>
struct foo
{
  typedef typename T::iterator it;

  std::vector<it> m_collection;
};

不推导出容器和包含类型?

【讨论】:

  • 很好的答案。你的第一个建议看起来很完美。谢谢。
【解决方案2】:

这是一个最小的运行示例,其中foo 可以在序列容器之间切换以存储it

#include <vector> 
#include <deque> 
#include <list> 

template
<
    typename T, 
    template<typename, typename> class SequenceContainer,
    template <typename> class Allocator = std::allocator
>
struct foo
{
    typedef typename SequenceContainer<T, Allocator<T>>::iterator it;

    SequenceContainer<it, Allocator<it>> m_collection;
};

using namespace std; 

int main()
{
    foo<double, vector> vecFoo; 
    foo<double, deque>  dequeFoo; 
    foo<double, list>   listFoo; 

    return 0;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-06
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 2011-10-19
    • 2013-11-30
    • 1970-01-01
    相关资源
    最近更新 更多