Вопрос

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;
    }
Это было полезно?

Решение

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;
 ....
};

Другие советы

juanchopanza answered about container's typedef, but there is another way.

All std containers have begin() method. To get it's type, use decltype. So, your method would be :

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

I still find the way juanchopanza said better.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top