微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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));
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐