这个问题是在一次采访中问我的。我仍在寻找这个问题的解决方案。
以下两种类型的函数(两者或一种)可以存在于具体类中:
ostream& prettyPrint(ostream& ost) const;
std::string toString() const;
我们的目标是设计一个
PrettyPrint
支持这两种实现的模板类。
PrettyPrint
在我写的优先级中使用具体类的函数:如果两者都存在,则使用第一个,否则使用第二个。
// ******* 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;
}