How to get the type of stl container from object?

c++, stl

Solution

C++11 has some nice simple ways:

auto it = container.begin();

Or equivalently:

decltype(container.begin()) it = container.begin();

Or even:

decltype(container)::iterator it = container.begin();

Nonetheless, even if you can't use type deduction, you should never be in a situation where you couldn't type out the type in some form or another (perhaps involving template parameters). If the compiler knows what type it is, so do you.

Problem

How to get the type of STL container from an object? For example, I have a `container` variable and I know that it is `std::vector<some type>`. I need to iterate the container using iterators. Is there a way to declare iterator without knowing the type of container? I can get the type from the code of course, but I am curios to do it without using the type. Also I am not using C++11.

Original source