Boost logo

Boost :

From: Fernando Cacciola (fcacciola_at_[hidden])
Date: 2001-06-13 17:43:25

{just for the records: I've just came back from my 1-month holidays, and
I've found more than 1000 new boost messages!
 There's a lot of work going on here... but it's hard to keep track of the
relevant threads, though.
BTW, how do you manage to organize the boost forum. Outlook Express doesn't
collapse e-mails by thread, so I have to do it manually}

----- Original Message -----
From: Luis Pedro Coelho <deepblack9_at_[hidden]>
To: <boost_at_[hidden]>
Sent: Wednesday, June 13, 2001 7:15 PM
Subject: [boost] A little utility class I'd like to contribute to boost

> I would like to contribute a small utility template I use. The code
> is so small, that I am posting it here in this email. The use of this
> is as a member object in place of builtin types, allowing you to define an
> initial value for it. Instead of writing something like:
> class X {
> int data;
> };
> you can write
> class X {
> auto_init<int> data;
> };
> and data gets initialized to zero. Or you can write
> class X {
> auto_init<int,5> data;
> };
> and data gets initialized to five. In every other aspect data behaves very
> much like a real int. It also serves an answer to the pleas by people to
> for C++ to allow stuff like
> class X {
> int data = 5;
> };
> like Java.
> The code is:
A few comments,

> template <typename T, T init = T()>

Given the intended usage for this class, I think that the 'init' value
should be always given.
This removes the 'default constructible' requirement on T imposed by the
default initialization of 'init'.

> struct auto_init {
> auto_init():object(init) { }
> auto_init(const T& other):object(other) { }
> operator T& () { return object; }
> operator const T& () const { return object; }
> T& operator = (const T& other) { object = other; return object; }
> void reset() { object = init; }
> private:
> T object;
> };
Since you are providing conversion operators, the constructor for T should
be explicit.
Therefore, auto_init's own copy constructor and assigment should also be

But there are other important issues to be addressed:
Ideally, auto_init<T> objects should inherit the semantics of the inner type
such as other operators (==,+,&, void const*, etc...) but that's tricky,
because T might not support some of the them.
Otherwise I won't be able to write expressions like: if ( data == 3 ), int
a = data + 1 , int* p = &data, if ( data ) ..., etc...

IMO, the simple interface you proposed it's just too simple to be generally
That is, all we need is to default initialize a data member, but we can't
afford loosing the possibility of writing expression as the ones above.

A full featured interface will work well for built in types (and most POD
types as well), so that can be usefull, but I'm not sure if we can define
something general enough.

Just thinking...

Fernando Cacciola
Sierra s.r.l.

Boost list run by bdawes at, gregod at, cpdaniel at, john at