Initializing simple POD (members) / value_initialized
Hi all!
For holding various configuration data items, we are considering using
some structs that would look like so:
struct subject {
size_t id;
std::wstring name;
double length;
// ...
};
struct subject_list {
std::wstring list_id;
std::vector<subject> subjects;
int position;
};
// ...
Now - I find it annoying, that to have proper default initialized POD
members, I would need to supply a default ctor that initializes all
members to zero. Bad for maintenance, as sooner or later someone will
forget to add a new member to the ctor list and then when a new struct
is used it ain't initialized properly.
When searching around, the only helper I found is
boost::value_initialized, but that is a more general approach for all
types and seems to be targeted at simplifying writing template code,
while what I want is as much transparency vs. the underlying POD type as
possible. (No get() or explicit casts.)
So, I tried to come up with something myself. Feel free to comment!
Notes:
* I think it should work for pointers, though I don't plan to use it for
these.
* It's not important if not 100% portable, because I'll use this on
Windows only.
[code]
//! struct value_init
//! Wrapper type, for numerical PODS or pointers
template<typename T>
struct value_init {
T x;
//! Default initialize to zero
value_init()
: x(0)
{ }
//! Note: default copy ctor and operator should be OK
//! from value
value_init(T val)
: x(val)
{ }
//! assign a value
T& operator=(T val) {
x = val;
return x;
}
//! convert to non-const underlying type
operator T&() {
return x;
}
//! convert to const underlying type
operator T const&() const {
return x;
}
//! make address-of operator return the pointer-type of the underlying type
//! (the numerical address value is the same anyway)
T* operator&() {
return &x;
}
//! const address-of operator
T const* operator&() const {
return &x;
}
};
[/code]
// usage:
struct subject {
value_init<size_t> id;
std::wstring name;
value_init<double> length;
// ...
};
cheers,
Martin
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]