Class fallback_variant_policy

Synopsis

#include <include/type_safe/variant.hpp>

template <typename Fallback>
class fallback_variant_policy

Description

A variant policy for [ts::basic_variant]() that uses a fallback type.

When changing the type of the variant throws an exception, the variant will create an object of the fallback type instead. The variant will never be empty. \requires Fallback must be nothrow default constructible and a type that can be stored in the variant. \module variant

Methods

change_value

Source

Lines 761-805 in include/type_safe/variant.hpp.

template <typename Fallback>
class fallback_variant_policy
{
    static_assert(std::is_nothrow_default_constructible<Fallback>::value,
                  "fallback must be nothrow default constructible");

public:
    using allow_empty = std::false_type;

    template <typename T, typename... Types, typename... Args>
    static void change_value(union_type<T> type, tagged_union<Types...>& storage, Args&&... args)
    {
        change_value_impl(type, storage, std::forward<Args>(args)...);
    }

private:
    template <typename T, typename... Types, typename... Args>
    static auto change_value_impl(union_type<T> type, tagged_union<Types...>& storage,
                                  Args&&... args) noexcept ->
        typename std::enable_if<std::is_nothrow_constructible<T, Args&&...>::value>::type
    {
        destroy(storage);
        // won't throw
        storage.emplace(type, std::forward<Args>(args)...);
    }

    template <typename T, typename... Types, typename... Args>
    static auto change_value_impl(union_type<T> type, tagged_union<Types...>& storage,
                                  Args&&... args) ->
        typename std::enable_if<!std::is_nothrow_constructible<T, Args&&...>::value>::type
    {
        destroy(storage);
        TYPE_SAFE_TRY
        {
            // might throw
            storage.emplace(type, std::forward<Args>(args)...);
        }
        TYPE_SAFE_CATCH_ALL
        {
            // won't throw
            storage.emplace(union_type<Fallback>{});
            TYPE_SAFE_RETHROW;
        }
    }
};





Add Discussion as Guest

Log in