c – 标准库容器的通用函数模板

我正在尝试编写一个简单的通用函数来迭代容器元素.每个元素都转换为std :: string(无论如何)并存储在另一个地方.基本版本是微不足道的:
template<class Container>
void ContainerWork(const Container& c)
{
    for(const auto& elem : c) {
        /* convert to string and store*/
    }
}

然后有必要为值类型为std :: string的容器添加特化,并将代码转换为:

template<typename T,template<typename,typename> class Container,class Allocator>
void ContainerWork(Container<T,Allocator> c)
{
    for(const T& elem : c) {
        /* convert to string and store*/
    }
}

template<template<typename,class Allocator>
void ContainerWork(Container<std::string,Allocator> c)
{
    for(const std::string& elem : c) {
        /* frame elem in quotes*/
    }
}

它工作得很好,但现在我只能使用有序的容器(矢量,列表等),但我也想使用set和unordered_set.任何想法如何没有“复制粘贴”实现4个容器的容器?我正在尝试使用decltype(Container):: value_type但没有运气.

我可能会使用大多数c 11功能(编译器 – VS2012或GCC 4.8.x)

解决方法

这就是为什么所有标准库的算法都适用于迭代器而不是容器.

您可以更改核心功能以处理迭代器而不是容器.这将需要部分特化,这对于函数模板是不存在的,因此我们将使用委托到类的技巧:

template <typename It>
void DoIteratorWork(It start,It end)
{
  DoIteratorWork_Impl<It,typename std::iterator_traits<It>::value_type>::call(start,end);
}

template <typename It,typename ValueType>
struct DoIteratorWork_Impl
{
  static void call(It start,It end)
  {
    for (; start != end; ++start) {
      // operate on *it
    }
  }
};

template <typename It>
struct DoIteratorWork_Impl<It,std::string>
{
  static void call(It start,It end)
  {
    for (; start != end; ++start) {
      // operate on *it
    }
  }
};

如果你真的想,你可以创建一个包装器:

template <class Container>
void DoContainerWork(const Container& c)
{
  using std::begin; using std::end; // enable ADL of begin and end
  return DoIteratorWork(begin(c),end(c));
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...