Search code examples
c++templatesiostream

Choose stdout or stderr based on function argument


I want to create a template that prints any container which its element can be printed by std::cout or any other stream.

I want to be able to tell which stream it should print into, therefore somehow I need to pass the target stream as an arguemnt? Below is the code that I came up with. But there are couple of problems that I havent figured out yet

If I use fprintf() then I can directly pass the stream as argument to fprintf but then the problem is the element need to be a char * while std::cout will take care of type conversion I suppose much easier?

template<template<typename...> typename C, typename E, typename S>
void my_printer(const C<E>& container,
                     S separator = ' ',
                     FILE *stream = stdout) {

  typename C<E>::size_type index = 0;
  typename C<E>::size_type lastIndex = container.size() - 1;

  for (const auto& element: container) {
    if (stream == stdout) {
      std::cout << element;
      if (index < lastIndex) {
        std::cout << separator;
      }
    } else if (stream == stderr) {
      std::cerr << element;
      if (index < lastIndex) {
        std::cerr << separator;
      }
    }
    index++;
  }
  
}

Solution

  • Change the parameter to a std::ostream &:

    template<template<typename...> typename C, typename E, typename S>
    void my_printer(const C<E>& container,
                         S separator = ' ',
                         std::ostream &stream=std::cout) {
    

    Now, you can pass either std::cerr or, explicitly, std::cout if you feel like it, and then use all the regular stream formatted operations.