我有類似下面一個很簡單的測試程序: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') 。它不能兼而有之。 –