【发布时间】:2017-06-20 14:00:58
【问题描述】:
我有一个非常简单的测试程序,如下所示:
#include<vector>
#include<iostream>
using namespace std;
template<typename C, typename E>
void f(const C<E>& container){
cout<<container.size()<<endl;
}
int main(){
vector<int> i;
f(i);
return 0;
}
使用 gcc 4.1.2 编译失败。错误信息是:
templateContainer.cpp:5: error: ‘C’ is not a template
templateContainer.cpp: In function ‘int main()’:
templateContainer.cpp:10: error: no matching function for call to ‘f(std::vector<int, std::allocator<int> >&)’
【问题讨论】:
-
这就是容器具有关联类型的原因。你不需要
E;只需写typename C::value_type(或typename C::reference_type,视情况而定)。 -
澄清一下,错误消息是因为
C被定义为类型的名称 (typename C),但它被使用作为模板的名称 (C<E>)。不能两者兼有。
标签: c++ class templates containers typename