c++ how to use template class as [type parameter] when defining template function?

326 Views Asked by At

I am trying to write a template function, which could accept generic-typed containers like std::vector/list, to do some work, like this:

template<typename T, typename Container>
void useContainer(const Container<T>& container) {
}

Then in main function I can:

    vector<int> vi;
    useContainer(vi); // compilation error, see below

// or
    deque<char> dc;
    useContainer(dc);

Well it doesn't compile, clang++ reports following error lines.

error: expected ')'
void useContainer(const Container<T>& container) {

note: to match this '('
void useContainer(const Container<T>& container) {

note: candidate template ignored: couldn't infer template argument 'T'
void useContainer(const Container<T>& container) {
     ^
2 errors generated.

To be honest, I don't quite get what this error message actually indicates, which doesn't give me much hints about where I got wrong.

How to fix this, and make my function able to accept different STL containers as parameter? Or do we need to specify some template's template(embedded template?) What technique is needed here?

Thanks!

2

There are 2 best solutions below

0
user12002570 On BEST ANSWER

The correct way to do this would be by using template template parameter as shown below:

//use template template parameter
template<  template<typename W, typename Alloc = std::allocator<W>>typename Container, typename T>
void useContainer(const Container<T>& container) {
}

int main(){
     vector<int> vi;
    useContainer(vi); //works now
}

Working demo

2
apple apple On

you can simple use generic type.

if the code works whether Container is std::vector or std::deque, then it would work without specify the container type at all.

template<typename T>
void useContainer(const T& container){
   for(auto& v:container) // for example, they both support range-based-for
      do_something(v);
}