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

Suppose we need a function that returns something. But this cannot be found. I see the options:

1. T find(bool &ok); //return default T value if not found

We can create a structure:

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 execute the function:

2. CheckableValue<T> find();

Or we can use:

3.boost::tuple<bool, T> find()

What do you think is preferable?

+5
source share
2 answers

I prefer:

4. boost::optional<T> find();

The problem with the tuple is that the part is Tinvalid when the part boolis false; this behavior is not performed by the tuple. The CheckableValue class is the same solution as boost::optionalfor the same problem.

+13
source

returns something. But something cannot be found.

- ? "not found" , "" -.

NULL .

0