I am trying to write a function which can take any of the standard containers(list, stack, vector etc) as it’s arguments. I also wish to know the type that is within the container. Here is what I have tried.
#include<iostream>
#include<list>
#include<vector>
template<class data_type, template<class> class container_type>
void type(container_type<data_type>& _container){
std::cout<<typeid(container_type).name()<<std::endl;
}
int main(){
std::list<int> list_t;
std::vector<int> vector_t;
type(list_t);
type(vector_t);
}
The type of container_type once inside this function is always _Container_base_aux_alloc_empty which(I think) is a base class of the standard containers.
What is going on here?
How would I make this function return the correct type?
Your code won’t work, because as soon as someone swaps out the allocator or something like that, then you’re done for. You should take any T and use
::value_type, if in C++03, or type deduction in C++0x.Also,
.name()isn’t defined to return anything useful, at all. In any situation. An implementation could return “har har sucker! good luck using this language feature” for every type and be conforming.