c++ - 如何将迭代器泛化为某种类型

标签 c++ templates generics iterator containers

考虑这两个函数,它们对于 std::vector 效果很好:

  int connectNode(GraphNode const& newNode,std::vector<GraphNode const*>::const_iterator beginCandidates, std::vector<GraphNode const*>::const_iterator endCandidates){
    int connections =0;
    for (auto iter= beginCandidates; iter!=  endCandidates; ++iter) {
      if(connectNodes(newNode,**iter)) ++connections;
    }
    return connections;
  }

  int connectNode(GraphNode const& newNode,std::vector<GraphNode>::const_iterator beginCandidates, std::vector<GraphNode>::const_iterator endCandidates){
    int connections =0;
    for (auto iter= beginCandidates; iter!=  endCandidates; ++iter) {
      if(connectNodes(newNode,*iter)) ++connections;
    }
    return connections;
  }

这些函数适用于 vector ,但显然不适用于任何其他容器,例如一套。怎么能一概而论呢。我能想到的唯一可能的解决方案是使用一些相当丑陋的enable_if解决方法。有直接的解决方案吗? 编辑: 为了更清楚地说:我想要两个函数,一个用于普通容器,一个用于指针容器。真正的逻辑发生在 connetNodes 内部,它需要两个引用。 (注意第一个函数中的 **)

最佳答案

正如前面所说,让迭代器输入一个模板参数 - 这解决了泛化迭代器本身的问题。对于普通 GraphNode 值及其指针之间的差异,您可以使用重载:

template<class T>
T& maybe_deref(T& v){ return v; }

template<class T>
T& maybe_deref(T* p){ return *p; }

只需在 connectNodes(newNode, Maybe_deref(*iter)) 中调用即可。

关于c++ - 如何将迭代器泛化为某种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15535526/

相关文章:

Java 泛型、接口(interface)和类继承

c++ - 处理模板创建的更好方法?

java - OSGi 客户端从 JavaEE 服务器访问 EJB 中的 RMI ClassCastException

c++ - 为什么函数以相反的顺序显示十六进制代码?

c++ - C++ 模板资源

c++ - 模板偏特化

wpf - 你能在数据绑定(bind)的 WPF 样式中执行 "math"吗

c# - 无法完全抽象数据访问方法

c++ - 使用MAP文件 VS2010 MFC

c++ - 有关指针解引用的C++技术问题