【发布时间】:2011-04-04 10:54:32
【问题描述】:
我正在尝试构建一个模板函数。使用内部模板类,我想将函数的模板类型传递给这些类。所以我有:
template <class T>
T find_bottleneck (ListGraph &g, CrossRefMap<ListGraph, Edge, T> &weight, Node &s, Node &t) {
// Check if theres a single edge left
if (countEdges(g) == 1) {
CrossRefMap<ListGraph, Edge, T>::ValueIt itr = weight.beginValue();
return *itr;
}
然而这失败了,引用
lemon_graph.cpp: In function ‘T find_bottleneck(lemon::ListGraph&, lemon::CrossRefMap<lemon::ListGraph, lemon::ListGraphBase::Edge, T>&, Node&, Node&)’:
lemon_graph.cpp:20: error: expected ‘;’ before ‘itr’
lemon_graph.cpp:21: error: ‘itr’ was not declared in this scope
我尝试使用一个简单的函数示例重新创建它,该函数根据传递给它的类型生成向量并且编译良好,所以我不确定问题出在哪里。
【问题讨论】:
-
会是一个简单的“返回 *(weight.beginValue());”工作吗?
-
你正在一个类模板中制作一个函数模板。
-
@sbi:我是?我以为 find_bottleneck 是一个函数模板
-
我指的是您的“模板函数....模板类”。它是函数模板和类模板。 (尽管这种差异听起来微不足道,但它很重要。类模板不是类,它是可以从中生成类的模板。这就是为什么你不能在类型所在的地方使用类模板的名称预期:
std::vector<std::deque>不会编译,因为std::deque不是一个类。但是,std::deque<int>是,所以std::vector< std::deque<int> >有效。函数模板类似。)
标签: c++ templates class function