Skip to content

Instantly share code, notes, and snippets.

@juaxix
Created January 1, 2019 21:08
Show Gist options
  • Save juaxix/10512b6379fb90a8f2ed8851a34076a1 to your computer and use it in GitHub Desktop.
Save juaxix/10512b6379fb90a8f2ed8851a34076a1 to your computer and use it in GitHub Desktop.
Builder Coding Exercise
#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;
}
};
#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