Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good to use boost::tuple<bool, T> to indicate if T was found or not?

Tags:

c++

boost

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 ?

like image 878
Andrew Avatar asked Mar 16 '12 08:03

Andrew


1 Answers

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.

like image 190
thiton Avatar answered Sep 20 '22 21:09

thiton