Builder Coding Exercise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <ostream> | |
#include <vector> | |
using namespace std; | |
struct Field | |
{ | |
string name; | |
string type; | |
}; | |
class Code { | |
protected: | |
string name; | |
vector<Field> fields; | |
public: | |
Code() {} | |
Code(const string& class_name) : name(class_name) {} | |
Code(Code&& other) | |
: name{ move(other.name) }, | |
fields{ move(other.fields) } | |
{ | |
} | |
Code(Code& other): name{ move(other.name) }, | |
fields{ move(other.fields) } | |
{ | |
} | |
Code& operator=(Code&& other) noexcept | |
{ | |
if (this == &other) | |
return *this; | |
name = move(other.name); | |
fields = move(other.fields); | |
return *this; | |
} | |
friend ostream& operator<<(ostream& os, const Code& obj) | |
{ | |
os << "class " << obj.name << endl << "{" << endl; | |
for (auto& field : obj.fields) | |
{ | |
os << " " << field.type << " " << field.name << ";" << endl; | |
} | |
os << "};" << endl; | |
return os; | |
} | |
friend class CodeBuilder; | |
}; | |
class CodeBuilderBase { | |
protected: | |
Code& code; | |
explicit CodeBuilderBase(Code &code) : code{ code } {} | |
public: | |
operator Code() const { return move(code); } | |
}; | |
class CodeBuilder : public CodeBuilderBase | |
{ | |
Code c; | |
public: | |
CodeBuilder(const CodeBuilder& cb) : CodeBuilderBase{c} { | |
c = std::move(cb.code); | |
} | |
CodeBuilder(const string& class_name) : CodeBuilderBase { c } | |
{ | |
c.name = class_name; | |
} | |
CodeBuilder& add_field(const string& name, const string& type) | |
{ | |
c.fields.push_back({ name, type }); | |
return *this; | |
} | |
friend ostream& operator<<(ostream& os, const CodeBuilder& obj) | |
{ | |
return os << obj.c; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cstdio> | |
#include <string> | |
#include <vector> | |
#include <fstream> | |
#include <tuple> | |
#include <sstream> | |
#include <memory> | |
#include "Code.hpp" | |
using namespace std; | |
int main() | |
{ | |
auto cb = CodeBuilder{ "Person" } | |
.add_field("name", "string") | |
.add_field("age", "int"); | |
cout << cb << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment