这可能是一个微不足道的问题,但让我发疯。
我想定义一个函数 foo()
这将适用于不同的容器,例如:
vector<int>
, vector<double>
, set<int>
和 set<double>
.
我试过这样定义 foo:
template<typename CONT, typename T>
int foo(CONT<T>){
//evaluate x
return (int) x ;
}
这种定义是行不通的,但我不明白为什么。
我怎样才能实现类似的目标?
最佳答案
同时指定容器类模板及其实例化的方法是使用template模板参数:
template <template <typename...> class Cont, typename T>
int foo(Cont<T>) {
...
}
请注意,Cont
使用了可变数量的参数,否则它不会覆盖标准容器具有的未知数量的默认模板参数。
关于c++ - 如何创建容器和类型都是参数的模板函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12965082/