C++ Get Vector type

There are two ways to accomplish this.

1) Either you make use of the fact that std::vector<> (like all standard library container classes) maintains a member type value_type, which represents the type of the elements stored in the vector. So you can do this:

template <typename T> void SomeFunc() {
  typename T::value_type s;  // <--- declares a `std::string` object
                             //      if `T` is a `std::vector<std::string>`
}

2) Or else, you change the declaration of your function and make use of template template parameters:

template <template <typename> class T, typename Elem>
void SomeFunc(T<Elem> &arg)
{
  Elem s;
}

However, there is a small problem with that: std::vector is really a template with two parameters (element type and allocator type), which makes it a little difficult to use the template template parameters and still keep the syntax simple. One thing that worked for me is to declare an alias of the vector type that leaves only one template parameter:

template <typename Elem>
using myvector = std::vector<Elem>;

Then I can use SomeFunc like this:

int main()
{
  myvec<std::string> vec;
  SomeFunc(vec);
}

In c++11, you can use decltype and std::decay to that effect:

std::vector<int> vec; using T = typename std::decay<decltype(*vec.begin())>::type;