/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <iostream>
#include <functional>
#include <sstream>
#include <map>
using namespace std;
template <class T>
class Prop
{
public:
Prop(const std::string &key, const std::function<void(std::string, std::string)> &changed);
private:
std::string Key;
T Value;
std::function<void(std::string, std::string)> changed;
public:
void operator=(const T &value) {
this->Value = value;
this->changed(this->Key, static_cast<ostringstream&>(ostringstream() << value).str());
}
};
template <class T>
Prop<T>::Prop(const std::string &key, const std::function<void(std::string, std::string)> &changed)
{
this->Key = key;
this->changed = changed;
}
class TheList
{
private:
std::map<std::string, std::string> theList;
protected:
void Update(const std::string &key, const std::string &value);
public:
std::string ToJson();
};
void TheList::Update(const std::string &key, const std::string &value)
{
theList[key] = value;
}
// TODO: body of this method will change and will use a processing library.
std::string TheList::ToJson()
{
std::string json = "{\n";
for (auto it : theList)
{
json += "\t\"" + it.first + "\": " + "\"" + it.second + "\",\n";
}
json.pop_back();
json.pop_back();
json += "\n}";
return json;
}
// A Serializable object.
class User : public TheList
{
public:
User();
public:
Prop<std::string> Name;
Prop<short> Age;
Prop<std::string> Address;
};
User::User() : Name("Name", std::bind(&User::Update, this, std::placeholders::_1, std::placeholders::_2)),
Age("Age", std::bind(&User::Update, this, std::placeholders::_1, std::placeholders::_2)),
Address("Address", std::bind(&User::Update, this, std::placeholders::_1, std::placeholders::_2))
{
}
int main()
{
User user;
user.Name = "Pamela";
user.Age = 25;
user.Address = "USA";
std::string json = user.ToJson();
cout << json << endl;
return 0;
}