I'm toying around with shift/io stream operator overloads and I was wondering if there is a way to pass additional arguments to the function, while still defining a default value for simpler syntax?
Considering the simple example:
#include <vector>
#include <iostream>
inline std::ostream& operator<<(std::ostream& ostream, const std::vector< int >& data) {
ostream << data[0];
for (int idx = 1; idx < data.size(); idx++) {
ostream << "," << data[idx]; // pass ',' as argument?
}
return ostream;
}
I'm looking to pass the delimiter character , to the function e.g. perhaps through a stream modifier:
std::cout << std::vector<int>(3, 15) << std::endl; // 15,15,15
std::cout << delimiter(;) << std::vector<int>(3,15) << std::endl; // 15;15;15
I've written a simple class that does this, but the resulting syntax is not very clean (requires forcing member operator overload to be called first):
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
class formatted{
public:
explicit formatted(const std::string& sequence = ",") : delimiter(sequence) { }
template < typename T >
std::string operator<<(const T& src) const {
std::stringstream out;
if (src.size()) {
out << src[0];
for (int i = 1; i < src.size(); i++) {
out << delimiter << src[i];
}
}
return out.str();
}
protected:
std::string delimiter;
};
template < typename T >
inline std::ostream& operator<<(std::ostream& ostream, const std::vector< T >& data) {
ostream << (formatted() << data);
return ostream;
}
int main(int argc, char const *argv[]) {
std::vector< int > data(10, 5);
std::cout << data << std::endl; // 5,5,5...5,5
std::cout << (formatted("/") << data) << std::endl; // 5/5/5...5/5
return 0;
}
Is there a way to simplify this, without the need of a helper class, or through the use of conventional stream manipulators?