|
Boost : |
From: Greg Chicares (chicares_at_[hidden])
Date: 2001-08-26 19:49:11
Given
struct S
{ int i0; int i1; double d0; std::string s0;};
I would like to be able to write
S s;
s["i0"] = "999.9"; // truncates to int
s["i1"] = "888e3"; // converts to int
s["d0"] = "777"; // converts to double
s["s0"] = "hello";
such that
std::cout << s.i0 << " " << s.i1 << " "
<< s.d0 << " " << s.s0 << "\n";
returns
999 888000 777 hello
This can be done by adding a symbol table to 'S' and
'ascribing' each member to the symbol table in the ctor:
struct S : public MemberSymbolTable<S>
{
int i0; int i1; double d0; std::string s0;
S() : i0(0), i1(0), d0(0.0)
{
ascribe("i0", &S::i0);
ascribe("i1", &S::i1);
ascribe("d0", &S::d0);
ascribe("s0", &S::s0);
}
};
I find this useful e.g. for cgi-bin where potentially many
name-value pairs like
{"i0", 123}
would otherwise need to be treated as
s.i0 = lexical_cast<int> (GetValue(cgi_data, "i0"));
s.d0 = lexical_cast<double> (GetValue(cgi_data, "d0"));
and yet a strongly-typed struct is wanted downstream instead
of a heterogeneous property map.
That was my original motivation, but there are other uses
as well. For instance, sometimes I need to calculate a CRC
of all members of a struct, and this makes it easier than
writing CRC(s.i0) + CRC(s.i1) + ... .
Is anyone interested in seeing the implementation?
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk