Boost logo

Boost :

From: Howard Hinnant (hinnant_at_[hidden])
Date: 2002-03-07 13:07:51


On Thursday, March 7, 2002, at 12:41 PM, David Abrahams wrote:
> From: "Howard Hinnant" <hinnant_at_[hidden]>
>> There are always ways to initialize an object. But once
> initialization
>> is made mandatory, getting an uninitialized object becomes more
>> difficult. Mandatory initialization goes against the "don't pay for
>> what you don't use" philosophy of C.
>
> It's not mandatory:
>
> template <class T>
> struct uninitialized
> {
> T value;
> operator T const&() const { return value; }
> };

Initialization is mandatory for std::complex and std::vector. :-\

Agreed initialization isn't always mandated in C++. Thank goodness.
Else we wouldn't even have the chance to work our way out of this
problem.

> Hmm, I'm unconvinced. If you're trying to write generic code, I don't
> think you should have to write this just to call a function with a
> default-constructed value:
>
> template <class T, void (*f)(T), bool is_scalar =
> boost::is_scalar<T>::value>
> struct call_with_default_constructed
> {
> static void execute() { f(T()); }
> };
>
> template <class T, void (*f)(T)>
> struct call_with_default_constructed<T,f,true>
> {
> static void execute() { f(T(0)); }
> }
>
> And you'd need a combinatoric suite of these just to make it work for
> multiple arguments.

A std::function could've come to the rescue for this use:

namespace std
{

namespace detail
{

template <class T>
inline
T
default_value(int2type<true>) // is scalar
{
     return T(0);
}

template <class T>
inline
T
default_value(int2type<false>) // is not scalar
{
     return T();
}

} // detail

template <class T>
inline
T
default_value()
{
     return detail::default_value<T>(int2type<is_scalar<T>::value>());
}

} // std

Now in your generic code you can:

f(std::default_value<T>(), std::default_value<U>());

map::operator[] could've used something like this.

But this is all rather academic, as I am not proposing that we change
the language in this way. I think the backward compatibility hit would
be way too large.

-Howard


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