この質問はインタビューで私に尋ねられました。私はまだこの質問の解決策を探しています。
次の 2 種類の関数 (両方または 1 つ) は、具象クラス内に存在できます。
ostream& prettyPrint(ostream& ost) const;
std::string toString() const;
私たちの目標は、
PrettyPrint
両方の種類の実装をサポートするテンプレート クラスを設計することです。
PrettyPrint
私が書いた優先順位で具象クラスの関数を使用します。両方が存在する場合、最初のものが使用され、そうでない場合は2番目が使用されます。
// ******* 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;
}