Skip to content

Alternative to bad_variant_access #21

@jcelerier

Description

@jcelerier

Hello,

Do you think that it would be possible to have an alternative to the current apply mechanism, which would call an operator()() with no arguments instead of throwing ?

A bit like this (but without the overhead of try...catch) :

template<typename Visitor, typename... Variants>
auto apply_noexcept(Visitor&& v, Variants&&... vars) noexcept
    -> decltype(auto)
{
    try {
        return eggs::variants::apply(v, std::forward<Variants>(vars)...);
    }
    catch(const eggs::variants::bad_variant_access& e) {
        return v();
    }
}


int main() 
{
    eggs::variant<int, float> var;
    struct vis {
            int operator()(int) { return 0; }
            int operator()(float) { return 1; }
            int operator()() { return 2; }
    } v;

    auto res = apply_noexcept(v, var);
    assert(res == 2);
}

This is because sometimes types have a meaningful "null" value, and I find it better to just use the variant's null state, than make a variant<some_null_type, ...>.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions