// output
Code: Select all
widget "a"
{
p : 2 2
s : 2 2
t : hi
children:
widget "b"
{
p : 3 3
s : 2 2
t : hi
children:
}
printed widget "b"
widget "c"
{
p : 0 0
s : 0 0
t :
children:
widget "d"
{
p : 4 4
s : 0 0
t :
children:
}
printed widget "d"
}
printed widget "c"
}
printed widget "a"
Code: Select all
wPtr a(new widget("a"));
a <<
position(2, 2) <<
size(2, 2) <<
text("hi") <<
callback(EVT_PRINT, boost::bind(&printCallback, _1)) <<
(
wPtr(new widget("b")) <<
position(3, 3) <<
text("hi") <<
size(2, 2) <<
callback(EVT_PRINT, boost::bind(&printCallback, _1))
) <<
(
wPtr(new widget("c")) <<
callback(EVT_PRINT, boost::bind(&printCallback, _1)) <<
(
wPtr(new widget("d")) <<
position(4, 4) <<
callback(EVT_PRINT, boost::bind(&printCallback, _1))
)
);
a->print(0);
Code: Select all
#include <string>
#include <iostream>
#include <list>
#include <map>
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
struct position
{
float x, y;
position(float x = 0, float y = 0): x(x), y(y) {}
};
struct size
{
float w, h;
size(float w = 0, float h = 0): w(w), h(h) {}
};
struct text
{
std::string str;
text(const std::string &str = ""): str(str) {}
};
class widget;
struct callback
{
int code;
boost::function<void(widget*)> func;
callback(int code, const boost::function<void(widget*)> &func): code(code), func(func) {}
};
typedef boost::shared_ptr<widget> wPtr;
enum
{
EVT_PRINT
};
struct widget
{
std::string name;
widget(const std::string &name): name(name) {}
position p;
widget &operator <<(const position &p) { this->p = p; return *this; }
size s;
widget &operator <<(const size &s) { this->s = s; return *this; }
text t;
widget &operator <<(const text &t) { this->t = t; return *this; }
std::list<wPtr> w;
widget &operator <<(const wPtr &w) { this->w.push_back(w); return *this; }
std::map<int, boost::function<void(widget*)> > callbacks;
widget &operator <<(const callback &c) { callbacks[c.code] = c.func; return *this; }
void print(int tabs)
{
tab(tabs) << "widget \"" << name << "\"\n";
tab(tabs) << "{\n";
tab(tabs) << "\tp : " << p.x << " " << p.y << "\n";
tab(tabs) << "\ts : " << s.w << " " << s.h << "\n";
tab(tabs) << "\tt : " << t.str << "\n";
tab(tabs) << "\tchildren:\n";
for (std::list<wPtr>::iterator i = w.begin(); i != w.end(); ++i)
{
(*i)->print(tabs + 1);
}
tab(tabs) << "}\n";
std::map<int, boost::function<void(widget*)> >::iterator i = callbacks.find(EVT_PRINT);
if (i != callbacks.end())
{
i->second(this);
}
}
std::ostream &tab(int n)
{
for (int i = 0; i < n; ++i)
std::cout << '\t';
return std::cout;
}
};
template<typename T>
wPtr &operator <<(wPtr lhs, const T &rhs)
{
(*lhs) << rhs;
return lhs;
}
void printCallback(widget *w)
{
std::cout << "printed widget \"" << w->name << "\"\n";
}





