Re: Initializing simple POD (members) / value_initialized
On 28 Aug., 15:18, Goran <goran.pu...@gmail.com> wrote:
On Aug 27, 11:38 pm, "Martin T." <0xCDCDC...@gmx.at> wrote:
So, I tried to come up with something myself. Feel free to comment!
OK...
[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)
{ }
Yeah, we have a similar thing here at my work. We even added the
default value to the template, like so:
template<typename T, T Def=0>
struct value_init {
T x;
//! Default initialize to zero
value_init()
: x(Def) // Default value here
{ }
...
I'd say, yeah, why not?
Here are some reasons for why not:
1) It seems very unexpected for a user of value_init
that a different zero-initializer leads to a different
type.
2) value_init can only be used for integral types
and enumeration types, because of the usage in a
non-type template parameter.
If control of the default value is preferred, I suggest
a more general approach via an initializer trait class,
e.g.
template<typename T>
struct value_init_traits {
static T zero() { return T(); } // Could be constexpr in C++0x
... // Other useful properties
};
template<typename T>
struct value_init {
T x;
//! Default initialize to zero
value_init() : x(value_init_traits<T>::zero()) // Default value here
{ }
};
This would allow users to provide type-specific
zero-values. If really an instance-specific
customization is preferred, I still would use
the traits-route instead like this:
template<typename T, typename Tr = value_init_traits<T> >
struct value_init {
T x;
//! Default initialize to zero
value_init() : x(Tr::zero()) // Default value here
{ }
};
This does not have the unnecessary restrictions to
specific types.
Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]