Boost logo

Boost Users :

Subject: [Boost-users] [[value_initialized] when T is const
From: Edward Diener (eldiener_at_[hidden])
Date: 2009-09-19 01:44:40


I like the idea of using value_initialized for a variable to initialize
a value to its value intialized value when no initial value is given.
But if an initial value is given it does not work if the T is a const
type. Was this intended ?

Essentially if a variable is a non-const object, one can say, for example:

boost::value_initialized<int> data;
// data initialized to its value initialized value

boost::value_initialized<int> data;
boost::get(data) = arg;
// data is initialized to value arg

For a const value we have:
boost::value_initialized<int const> data;
// data initialized to its value initialized value

but we can not do:
boost::value_initialized<int> data;
boost::get(data) = arg; // ERROR
// try to initialize data to value arg

So there is no way to initialize a const T to a value when using
boost::value_initialized<T>. This presents a problem in a template class
where T can be a const type:

template <class T>
struct SomeTemplate<T>
{
boost::value_initialized<T> data;
SomeTemplate() { } // always good
SomeTemplate(T arg)
{
boost::get(data) = arg;
// FAILS with a const T,
// such as if SomeTemplate<int const> is instantiated with any int value
// as in 'SomeTemplate<int const> st(4);'
}
};

In this case boost::value_initialized can not be used.

This makes it much less usable in my estimation since the creator of a
template class wanting to use boost::value_initialized can only do so if
he restricts that template type to a non-const value. If he does not
make that restriction then he must go back to initialization by hand and
forgo the advantages of value_initialized entirely.

It would seem that this limitation could be lifted if the
boost::value_initialized template had a constructor which enabled one to
initialize the value in cases where initialization to a value
initialized state was not desired. Then, despite T being a const type,
one could initialize the variable to a specific value.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net