Search code examples
c++templatescontainersbehind

How to get the type of a container (e.g. int, double,...) from a template? C++


I am trying to create a C++-Printing-Function, which prints any STL-Container by the copy-algorithm and a userdefined header before.

My problem is, I have to print it by the copy-algorithm, so i would need the type of the template for the ostream_iterator ("ostream_iterator")?

How can i get the type of a container behind a template

(I tried it with typeid(cont) but it didn't work - Thanks!

 template<typename Container>
    void HeaderPrint(Container cont, std::string header = ""  )
    {
        std::cout << header << std::endl;
        copy(cont.begin(),cont.end(), ostream_iterator<typeid(cont)>(cout," "));
        std::cout << std::endl;
    }

Solution

  • Standard library containers define value_type with the container type:

    copy(cont.begin(),cont.end(), ostream_iterator<typename Container::value_type>(cout," "));
    

    If you are using your own container class, it would be wise to use this convention too:

    template <typename T>
    class MyContainer
    {
     public:
      typedef T value_type;
     ....
    };