5

This section of code gives an error:

template <class T>
void print_vector(vector<T>& v, string sep)
{
    std::ostream_iterator<T> ostr_it(std::cout, sep) ;
    std::copy(begin(v), end(v), ostr_it);
}

main.cpp:17:30: error: no matching constructor for initialization of 'std::ostream_iterator<float>' std::ostream_iterator<T> ostr_it(std::cout, sep);

I am confused because if I do it outside the template function and output the vector directly there is no error:

vector<float> result(elements);
std::copy(begin(result), end(result), ostream_iterator<float>(cout, ", "));

What is wrong? Do I need to specialize each template function?

Barry
  • 286,269
  • 29
  • 621
  • 977
Ivan
  • 7,448
  • 14
  • 69
  • 134

1 Answers1

3

Since no answer was posted I guess I'll go ahead.

The signature for ostream_iterator accept's a C-string, and not a C++ string:

std::ostream_iterator(ostream_type& stream, const CharT* delim)

It has been chosen that implicit cast to char * from std::string is not desirable, as said here, so you get an error.

To make it work, you can simply cast the std::string yourself:

std::ostream_iterator<T> ostr_it(std::cout, sep);         // DOES NOT WORK
std::ostream_iterator<T> ostr_it(std::cout, sep.c_str()); // WORKS
Kostas
  • 4,061
  • 1
  • 14
  • 32
  • 1
    It would be good to also show some alternative correct code (I suppose `sep.c_str()`) – M.M May 08 '18 at 01:46