0

I would like to print the vector values in the friend overloaded operator <<.

The class is here:

#ifndef FOR_FUN_TESTCLASS_HPP
#define FOR_FUN_TESTCLASS_HPP

#include <utility>
#include <vector>
#include <string>
#include <ostream>

class TestClass {

public:
    TestClass(uint32_t i, std::string s, std::vector<uint32_t> v) : i_(i), s_(std::move(s)), v_(std::move(v)) {}

    friend std::ostream &operator<<(std::ostream &os, const TestClass &aClass) {
        os << "i_: " << aClass.i_
        << " s_: " << aClass.s_
        << " v_: " << aClass.v_; //compiler error
        return os;
    }

private:
    uint32_t i_ {0};
    std::string s_;
    std::vector<uint32_t> v_ {};
};

#endif //FOR_FUN_TESTCLASS_HPP

but when I invoke the main method, it does not compile

TestClass tc { 1, "one", {1,2,3}};
std::cout << tc << std::endl;

This is because the operator << does not know how to print the vector. I would like to stay in the method operator<< and print the vector. How is this done?

Error: error: no match for operator<< (operand types are std::basic_ostream and const std::vector)

I don't want to iterate using the for operator, I am looking for a smarted solution, ie copy the vector contents in the ostream?

Captain Nemo
  • 345
  • 2
  • 14

1 Answers1

1

This will do the job:

friend std::ostream &operator<<(std::ostream &os, const TestClass &aClass) {
    os << "i_: " << aClass.i_
    << " s_: " << aClass.s_
    << " v_: ";
    for(auto it : aClass.v_) 
        os << it<<' ';
    return os;
}

Live on Godbolt.

or with copy:

std::copy(aClass.v_.begin(), aClass.v_.end(),
                   std::ostream_iterator<uint32_t>(std::cout, ' '));

Live on Godbolt.

Oblivion
  • 7,176
  • 2
  • 14
  • 33