mdjdrn1
mdjdrn1

Reputation: 51

C++ Printing array to any output object (by function)

I'm trying to make a function, which can 'print' content of array to any output object. It's looking a little bit like this:

template <class T, class Z>
void print(T* array, int& size, Z& obj)
{
    for (int k = 0; k < size; k++)
        Z<< array[k] << " ";
    Z<< std::endl;
}

I want obj to be any output object like std::cout or any of fstream, so I could call it using:

print(arr_name, arr_size, std::cout)

or

std::ostream file;
print(arr_name, arr_size, file)

Unfortunately, in my current verion it doesn't work at all (errors involve '<<' operator). What's wrong? Is it even possible to create such function?

Upvotes: 0

Views: 181

Answers (1)

Jack
Jack

Reputation: 133577

You are not using the name of the argument but the type.

Z << array[k] << " ";

should be

obj << array[k] << " ";

In addition, passing the size as non-const reference doesn't make much sense as you'll need an l-value, const int& size would be better.

But this won't be so much generic in any case. The best solution would be to use iterators and skip plain C arrays totally, and use std::array as a replacement (which makes sense since you are working in C++):

template <class T, class Z>
void print(const T& data, Z& obj)
{
  for (const typename T::value_type& element : data)
    obj << element;
  obj << std::endl;
}

std::array<int, 5> data = {1,2,3,4,5};
std::vector<std::string> data2;
print(data, std::cout);
print(data2, std::cout);

Upvotes: 1

Related Questions