Question 6
Back to Exercise
Write a Builder class whose operator<< accepts strings, numbers and characters (returning *this for chaining) and whose str() returns the result; build an invoice line and a CSV row.
Solution
#include <iostream>
#include <string>
class Builder {
std::string s_;
public:
Builder& operator<<(const std::string& x) { s_ += x; return *this; }
Builder& operator<<(const char* x) { s_ += x; return *this; }
Builder& operator<<(char c) { s_ += c; return *this; }
Builder& operator<<(int n) { s_ += std::to_string(n); return *this; }
const std::string& str() const { return s_; }
};
int main() {
Builder line;
line << "Item: " << std::string("Notebook") << " x " << 3 << " = Rs " << 3 * 60 << '!';
Builder csv;
for (int i = 1; i <= 4; ++i) (i > 1 ? csv << ',' : csv) << i * i;
std::cout << line.str() << '\n' << csv.str() << '\n';
return 0;
}
Item: Notebook x 3 = Rs 180! 1,4,9,16
Each operator<< returns the builder by reference, which is what makes chaining possible – exactly like std::ostream.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!