0

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?

2
  • You basically want template <class Iter> void print(Iter begin, Iter end, std::ostream& os) { std::for_each(begin, end, [&](decltype(*begin) const& element) { os << element << "\n"; }); }. And use it with an array like this: int x[10]; print(begin(x), end(x), std::cout); Commented Mar 19, 2016 at 15:44
  • Note: int& size is nonsense (make it int size) Commented Mar 19, 2016 at 15:51

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Oh my god, I was sitting and trying to figure out what was wrong for more that an hour, what a foolish mistake. I would downvote my question if i could. ANYWAY, I fixed these things, but I still cannot use it with print(arr_name, arr_size, std::cout)
@mdjdrn1: you should provide a minimal non working example.
My bad, I'm looking look now at your example, using it in simple program and everything is alright. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.