考虑以下两个函数,它们对于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/