如何创建模板函数,其中容器和类型都是参数?

luc*_*one 0 c++ templates

这可能是一个微不足道的问题,但让我发疯.我想定义一个函数foo(),将与像不同的容器工作: vector<int>,vector<double>,set<int>set<double>.

我试图像这样定义foo:

template<typename CONT, typename T>
   int foo(CONT<T>){
      //evaluate x
      return (int) x ;
   }
Run Code Online (Sandbox Code Playgroud)

这种定义不起作用,但我不明白为什么.

我怎样才能达到类似的效果?

Die*_*ühl 6

指定容器类模板及其实例化的方法是使用模板模板参数:

template <template <typename...> class Cont, typename T>
int foo(Cont<T>) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

请注意,Cont使用可变数量的参数,否则它将不会涵盖标准容器具有的未知数量的默认模板参数.


Big*_*oss 5

考虑一下:

template< class ContainerT >
int foo( ContainerT const& c ) {
}
Run Code Online (Sandbox Code Playgroud)

然后ContainerT可以是任何东西,包括std::vector<int>,std::vector<std::string>甚至std::map<std::string, int>.因此,您不需要添加新的模板参数,如果您需要知道仅使用value_type容器的类型:

typedef typename ContainerT::value_type container_type; // Or T in your foo
Run Code Online (Sandbox Code Playgroud)