我有类似下面一个很简单的测试程序:C++:为什么模板不能用于推导容器和元素类型?
#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') 。它不能兼而有之。 –