Reputation: 10149
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>
.
I have tried to define foo like this:
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?
Upvotes: 0
Views: 88
Reputation: 154045
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.
Upvotes: 7
Reputation: 6914
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>
. 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:
typedef typename ContainerT::value_type container_type; // Or T in your foo
Upvotes: 5