【发布时间】:2013-03-20 21:55:37
【问题描述】:
考虑这两个函数,它们适用于 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;
}
这些函数适用于向量,但显然不适用于任何 otehr 容器,例如一套。怎么可能一概而论。我能想到的唯一可能的解决方案是使用一些非常丑陋的 enable_if 解决方法。有直接的解决方案吗? 编辑: 为了更清楚:我想要两个函数,一个用于普通容器,一个用于指针容器。真正的逻辑发生在 connetNodes 内部,它需要两个引用。 (注意第一个函数中的**)
【问题讨论】:
-
您是否需要强制它必须是
GraphNode的迭代器? -
@Drew Dormann:它应该是 GraphNode 或 Graphnode const*。问题是我需要值和指针。此时该类型也可以保持打开状态。
标签: c++ templates generics iterator containers