Assume we need a function that returns something. But that something can be not found. I see options:
1. T find(bool &ok); //return default T value if not found
We can make a struct:
template <typename T>
class CheckableValue
{
public:
    CheckableValue(),
    _hasValue(false)
    {
    }
    CheckableValue(const T &t):
    _value(t),
    _hasValue(true)
    {
    }
    inline bool hasValue() const {return _hasValue}
    const T &value() const
    {
        assert(hasValue());
        return _value;
    }
private:
    T _value;
    bool _hasValue;
};
and make the function:
2. CheckableValue<T> find();
Or we can use:
3.boost::tuple<bool, T> find()
What do you think is preferable ?
I prefer:
4. boost::optional<T> find();
The problem with the tuple is that the T part is invalid when the bool part is false; this behaviour is not enforced by the tuple. Your CheckableValue class is the same remedy as boost::optional for the same problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With