简体   繁体   English

如何在容器和类型均为参数的情况下创建模板函数?

[英]How create template functions where both the container and the type are parameters?

This might be a trivial question but is driving me crazy. 这可能是一个琐碎的问题,但却使我发疯。 I want to define a single function foo() that would work with different containers like: vector<int> , vector<double> , set<int> and set<double> . 我想定义一个单个函数foo() ,它可以与不同的容器一起使用,例如: vector<int>vector<double>set<int>set<double>

I have tried to define foo like this: 我试图这样定义foo:

template<typename CONT, typename T>
   int foo(CONT<T>){
      //evaluate x
      return (int) x ;
   }

This kind of definition doesn't work, but I can't understand why. 这种定义不起作用,但我不明白为什么。

How can I achieve something similar? 我怎样才能取得类似的成绩?

The way to specify both the container class template and its instantiation is to use template template parameters: 指定容器类模板及其实例化的方法是使用模板模板参数:

template <template <typename...> class Cont, typename T>
int foo(Cont<T>) {
    ...
}

Note that Cont is using a variable number of arguments because otherwise it wouldn't cover the unknown number of defaulted template arguments the standard containers have. 请注意, Cont使用了可变数量的参数,因为否则它将无法覆盖标准容器具有的未知数量的默认模板参数。

Consider this: 考虑一下:

template< class ContainerT >
int foo( ContainerT const& c ) {
}

Then ContainerT can be any thing, including std::vector<int> , std::vector<std::string> or even std::map<std::string, int> . 然后ContainerT可以是任何东西,包括std::vector<int>std::vector<std::string>甚至std::map<std::string, int> So you don't need to add a new template parameter and if you need to know the type just use value_type of your container: 因此,您不需要添加新的模板参数,并且如果您需要知道类型,则只需使用容器的value_type

typedef typename ContainerT::value_type container_type; // Or T in your foo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM