This question was asked to me in an interview. I am still searching for the solution of this question.
The following two types of functions (both or one) can be present inside a concrete class:
ostream& prettyPrint(ostream& ost) const;
std::string toString() const;
Our goal is to design a template Class
PrettyPrint
which support both kinds of implementation.
PrettyPrint
uses functions of concrete class in the priority I have written them: if both are present, the first will be used, else the second.
// ******* given code - start ********
struct LoginDetails {
std::string m_username;
std::string m_password;
std::string toString() const {
return "Username: " + m_username
+ " Password: " + m_password;
}
};
struct UserProfile {
std::string m_name;
std::string m_email;
ostream& prettyPrint(ostream& ost) const {
ost << "Name: " << m_name
<< " Email: " << m_email;
return ost;
}
std::string toString() const {
return "NULLSTRING";
}
};
// ******* given code - end ********
// Implement PrettyPrint Class
template <class T>
class PrettyPrint {
public:
PrettyPrint(){
}
};
int main() {
LoginDetails ld = { "Android", "Apple" };
UserProfile up = { "James Bond", "james@bond.com" };
// this should print "Name: James Email: james@bond.com"
std::cout << PrettyPrint <UserProfile> (up) << std::endl;
// this should print "Username: Android Password: Apple"
std::cout << PrettyPrint <LoginDetails> (ld) << std::endl;
}