|
Boost Users : |
Subject: Re: [Boost-users] [value_initialized] when T is const
From: Edward Diener (eldiener_at_[hidden])
Date: 2009-09-19 13:06:03
This is a correction to my OP. I give it again in full.
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 subsequently 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::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::get(data) = arg; // ERROR
// trying to initialize data to value arg fails
So there is no way to initialize a const T to a value when using
boost::value_initialized<T>. Essentially for a const type,
boost::value_initialized initializes the object to its value initialized
value and subsequently it can never be changed.
It can be argued that if one is specifying a const type and one wants to
initialize the object of that type to a non-value initialized value,
simply do not use boost::value_initialized.
But consider the problem in a template class where T might be a
non-const or a const type depending on how the user instantiates the
template class:
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, where T is passed to the template instantiation as a const
type, 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 in the
constructor, while keeping the current semantics which disallow changing
the value of a const type once it has been initialized.
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