我有一个非常简单的测试程序,如下所示:
#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> >&)’
最佳答案
您可以使用模板模板参数(请注意,std::vector
实际上采用多个模板参数[一种元素类型和一种分配器类型]) .:
template<template <typename...> class C, typename... E>
void f(const C<E...>& container){
cout<<container.size()<<endl;
}
如果不需要类型分解,可以简单地使用普通模板。
template<typename C>
void f(const C& container){
cout<<container.size()<<endl;
}
您还可以从 STL 容器中获取 typedef:例如,如果您想知道容器中元素的类型,value_type
就在那里。
template<typename C>
void f(const C& container){
using ValueType = typename C::value_type;
cout<<container.size()<<endl;
}
关于c++:为什么不能使用模板来推断容器和元素类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44655222/