Search code examples
c++functiontemplatesparameterstypename

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


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!


Solution

  • 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