Thursday, August 8, 2013

Problem with expected<T>

The realization of expected<T> in this blog has a bug. While using it I've write a code like follows:

expected<double> my_sqrt(double x) {
    if(x < 0) return expected<int>::from_exception(std::out_of_range("x"));
    return std::sqrt(x);

int main() {
    std::cout << *sqrt(-10) << std::endl;

You may suspect that the first variant of my_sqrt was returning expected<int> and I've just forgot to change types everywhere. I've gotten "0" instead of "Terminate called after...". There was called a ctor expected<double>::expected(AA... arguments) which had taken an instance of expected<int> as an argument and succeeded.

To avoid such mistakes following code should be added to expected<T> (not expected_common<T>):

template<typename U>
expected(expected<U>) = delete;

No comments:

Post a Comment