Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An std container inside a template method

Greetings.

I don't know very well how to explain myself, but I believe a piece of code will make you understand what I'm intenting to do :

template<class A, class B>
void myFunction(A<B>& list)
{
  typename A<B>::iterator current = list.begin();
  typename A<B>::iterator end = list.end();

  while (current != end)
  {
    current++;
  }
}

Where A is an STL container (vector, list...). It's like inception, but with templates : a template, inside a template, etc...

The thing is : what do you do when one of the params of your template is itself a template... and still want to support every types supported by this template.

This of course doesn't compile (it says 'A is not a template').

Does someone knows how to create such a template ?

like image 554
The-Snake Avatar asked Feb 27 '11 19:02

The-Snake


2 Answers

You are looking for a template template parameter

template<template<class T, class All = std::allocator<T> > class A, class B>
void myFunction(A<B>& list)
{
  typename A<B>::iterator current = list.begin();
  typename A<B>::iterator end = list.end();

  while (current != end)
  {
    current++;
  }
}

However, in your particular case, I think you'd be better off by just passing the intantiated container, that is,

template<class C>
void myFunction(C& list)
{
   ...
}

use like this

vector<char> v;
myFunction(v);

Your original code would have to be called like this:

myFunction<std::vector, char> (v)

which is much more verbose and has no particular benefit

like image 136
Armen Tsirunyan Avatar answered Oct 13 '22 22:10

Armen Tsirunyan


A and B will be concrete types (and not templates), thus A<B> makes no sense.

You can write your code this way:

template<class List>
void myFunction(List &list)
{
  typename List::iterator current = list.begin();
  typename List::iterator end = list.end();

  while (current != end)
  {
    current++;
  }
}

If you need to know what is the type of an element of that list, there is a typedef inside of the list for that:

typename List::value_type
like image 2
CygnusX1 Avatar answered Oct 13 '22 22:10

CygnusX1