Boost logo

Boost :

From: Fernando Cacciola (fcacciola_at_[hidden])
Date: 2002-08-21 15:16:10


Hi,

I'm about to pack up this utility class that we talked about recently, but I
need to settle on the semantics.

AFAICT, there are two choices:

A) Trivial approach without deep-constantness.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

template<class T>
class value_initialized
{
  public :

    value_initialized() : x() {}

    operator T&() { return x ; }
    T& data() { return x ; }

  private :

    T x ;
} ;

Semantics of (A):
~~~~~~~~~~~

int y = 0 ;

value_initialized<int> x ;

    // OK, uses "operator int&()" on 'x'
    (y == x)

    // OK, uses "operator int&()" on 'x'
    static_cast<int&>(x) = y ;

value_initialized<int const> cx ;

    // OK, uses "operator int const&()" on 'cx'
    (y == cx)

value_initialized<int> const x_c ;

    // WARNING! uses non-const "operator int&()" on 'x_c const'
    (y == x_c)

value_initialized<int const> const cx_c ;
    // WARNING! uses non-const "operator int const&()" on 'cx_c const'
    (y == cx_c)

B) Deep-constant but hacky approach:
~~~~~~~~~~~~~~~~~~~~~~~~~~

template<class T>
class value_initialized
{
  public :

    value_initialized() : x() {}

    operator T&() const { return get() ; }

    T& data() const { return get() ; }

  private :

    T& get () const { return const_cast< value_initialized<T>* >(this)->x
; }

    T x ;
} ;

Semantics of (B)
~~~~~~~~~~~

value_initialized<int> x ;

    // OK, uses "operator int&() const" on 'x'
    (y == x)

    // OK, uses "operator int&() const" on 'x'
    static_cast<int&>(x) = y ;

value_initialized<int const> cx ;

    // OK, uses "operator int const&() const" on 'cx'
    (y == cx)

value_initialized<int> const x_c ;

    // OK! uses "operator int&() const" on 'x_c const'
    (y == x_c)

    // May look weird since the wrapper itself is const!!
    // OK, uses "operator int&() const" on 'x const'.
    static_cast<int&>(x_c) = y ;

value_initialized<int const> const cx_c ;
    // OK! uses "operator int const&() const" on 'cx_c const'
    (y == cx_c)

Which one do you prefer?

I prefer (B) since, for instance, if I have a value_initialized<> object
handled through a 'const&', such as when they are fed to generic code with
the signature: foo( T const& );
With (A), inside foo(), I will get warnings about using non-const methods
for const objects.

Fernando Cacciola
Sierra s.r.l.
fcacciola_at_[hidden]
www.gosierra.com


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