Boost logo

Boost :

From: Gennaro Prota (gennaro_prota_at_[hidden])
Date: 2006-07-10 08:33:57


Hi guys,

I don't know how and how much boost:optional<> overlaps with this
(last time I checked it was different, but I know there's a proposal
in which the template has been changed), anyway: is there interest for
a Barton-Nackman's fallible<T> template? Basically the idea is
(warning: not compiled):

#include <assert.h>

template<typename T>
class fallible
{
public :
             fallible();
    explicit fallible(const T & value);

    bool is_valid() const;

    const T& value() const;
    operator T() const;

    const T& else_default_to(const T& default_value) const;

    void invalidate();
    void validate(const T& value); // alternative to operator=

private :

    T m_value;
    bool m_valid;

};

template<typename T>
fallible<T>::fallible()
 : m_valid(false)
{
}

template<typename T>
fallible<T>::fallible( const T& v )
 : m_value(v), m_valid(true)
{
}

template<typename T>
bool
fallible<T>::is_valid() const
{
    return m_valid;
}

template<typename T>
const T&
fallible<T>::value() const
{
    assert(m_valid); // <---
    return m_value;
}

template<typename T>
fallible<T>::operator T() const
{
    return value();
}

template<typename T>
const T&
fallible<T>::else_default_to(const T& default_value) const
{
    return is_valid()
        ? static_cast<const T&>(value())
        : static_cast<const T&>(default_value);
}

template<typename T>
void
fallible<T>::invalidate()
{
    m_valid = false;
}

template <typename T>
void
fallible<T>::validate(const T& value)
{
    m_value = value;
    m_valid = true;
}

--
[ Gennaro Prota, C++ developer for hire ]
[    resume:  available on request      ]

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