Boost logo

Boost :

From: Luis Pedro Coelho (deepblack9_at_[hidden])
Date: 2001-06-13 17:15:10


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 class
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 ask
for C++ to allow stuff like

class X {
        int data = 5;
};

like Java.

The code is:

template <typename T, T init = T()>
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;
};

Copyright is by me (I do not recall seeing this anywhere) but I place no
restrictions on the use of the above code.

I have added a little function called reset() to reset the object to its
initial value because I have found use for it. I originally kept the object
public, but have never found a need for it, so I changed it to private.

I think this small class could go into boost/utility.hpp.

What do you think?

Luis Pedro Coelho


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk