status-code icon indicating copy to clipboard operation
status-code copied to clipboard

An idea: Allow overloading operator `throw` to gradually switch from existing exception objects to `status_code`

Open YexuanXiao opened this issue 1 year ago • 0 comments

namespace std {
template <typename T>
auto operator throw(T t)
{
    if constexpr (requires {t.operator throw();})
        return t.operator throw();
    else
        return operator throw(t);
}
generic_code operator throw(errc e) noexcept
{
    return make_status_code(e);
}
generic_code operator throw(errc e) noexcept
{
    return make_status_code(e);
}
future_code operator throw(future_error e) noexcept
{
    return future_code(e.code());
}
}

std::operator throw is a customization point, similar to customization point objects, but it does not need to be explicitly called.

The compiler provides an option to change the behavior of throw expression:

If -enable-throw-overloads is on:

throw expr;

will transform to:

throw std::operator throw(expr);

This feature is opt-in, allowing the code to support both new and old exception objects simultaneously, without needing to maintain two versions (especially for the standard library). The transform applies before throwing, it is almost zero-cost.

Last year, I proposed this with the goal of simplifying the make_exception_object idiom, but recently I believe it helps users and the standard library transform to using Herbceptions.

YexuanXiao avatar Dec 08 '24 11:12 YexuanXiao