Custom Output Methods
Designing Flexible Printing Interfaces
1. Implementing toString() Method
struct Product {
std::string name;
double price;
std::string toString() const {
return "Product[" + name + ", $" +
std::to_string(price) + "]";
}
};
2. Configurable Output Method
class StructPrinter {
public:
enum class Format { COMPACT, VERBOSE, JSON };
template<typename T>
static std::string print(const T& obj, Format format = Format::COMPACT) {
switch(format) {
case Format::COMPACT:
return compactPrint(obj);
case Format::VERBOSE:
return verbosePrint(obj);
case Format::JSON:
return jsonPrint(obj);
}
}
};
Output Method Flowchart
graph TD
A[Custom Output Method] --> B[toString()]
A --> C[Configurable Formats]
A --> D[Serialization Techniques]
Output Method Comparison
Method |
Flexibility |
Performance |
Use Case |
Direct Printing |
Low |
High |
Simple Structs |
toString() |
Medium |
Medium |
Debugging |
Serialization |
High |
Low |
Complex Objects |
3. Serialization Approach
struct NetworkConfig {
std::string serialize() const {
std::ostringstream oss;
oss << "{"
<< "\"ip\":\"" << ip_address << "\","
<< "\"port\":" << port
<< "}";
return oss.str();
}
std::string ip_address;
int port;
};
Advanced Printing Techniques
4. Template-based Generic Printing
template<typename T>
class GenericPrinter {
public:
static void print(const T& obj, std::ostream& os = std::cout) {
os << "Object Details:" << std::endl;
printMembers(obj, os);
}
private:
template<typename U>
static void printMembers(const U& obj, std::ostream& os);
};
LabEx Development Patterns
5. Logging-Oriented Output
struct SystemLog {
std::string getMessage() const {
return "[" + timestamp + "] " + message;
}
std::string timestamp;
std::string message;
int severity;
};
Best Practices
- Keep output methods concise
- Support multiple output formats
- Use const and references
- Handle potential exceptions
- Consider performance implications
Error-Safe Output Method
class SafePrinter {
public:
template<typename T>
static std::string safeToString(const T& obj) {
try {
return obj.toString();
} catch (const std::exception& e) {
return "Printing Error: " + std::string(e.what());
}
}
};
- Minimize memory allocations
- Use string_view for non-owning references
- Prefer compile-time techniques
- Cache complex formatting results