Skip to content

Commit

Permalink
add get<T>() overloads for when T is stored in recursive_wrapper<T>
Browse files Browse the repository at this point in the history
also makes get<T>() a compile time error where T is not in Types... (ref #24)
  • Loading branch information
artemp committed Mar 4, 2015
1 parent 7dfdfa2 commit 36f1e12
Showing 1 changed file with 39 additions and 6 deletions.
45 changes: 39 additions & 6 deletions variant.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -601,7 +601,8 @@ class variant
type_index = detail::direct_type<T, Types...>::index;
}

template<typename T>
// get<T>()
template<typename T, typename std::enable_if<(detail::direct_type<T, Types...>::index != detail::invalid_value)>::type* = nullptr>
VARIANT_INLINE T& get()
{
if (type_index == detail::direct_type<T, Types...>::index)
Expand All @@ -610,11 +611,13 @@ class variant
}
else
{
throw std::runtime_error("in get()");
throw std::runtime_error("in get<T>()");
}
}

template<typename T>
template <typename T, typename std::enable_if<
(detail::direct_type<T, Types...>::index != detail::invalid_value)
>::type* = nullptr>
VARIANT_INLINE T const& get() const
{
if (type_index == detail::direct_type<T, Types...>::index)
Expand All @@ -623,10 +626,40 @@ class variant
}
else
{
throw std::runtime_error("in get()");
throw std::runtime_error("in get<T>()");
}
}

// get<T>() - T stored as recursive_wrapper<T>
template <typename T, typename std::enable_if<
(detail::direct_type<recursive_wrapper<T>, Types...>::index != detail::invalid_value)
>::type* = nullptr>
VARIANT_INLINE T& get()
{
if (type_index == detail::direct_type<recursive_wrapper<T>, Types...>::index)
{
return (*reinterpret_cast<recursive_wrapper<T>*>(&data)).get();
}
else
{
throw std::runtime_error("in get<T>()");
}
}

template <typename T,typename std::enable_if<
(detail::direct_type<recursive_wrapper<T>, Types...>::index != detail::invalid_value)
>::type* = nullptr>
VARIANT_INLINE T const& get() const
{
if (type_index == detail::direct_type<recursive_wrapper<T>, Types...>::index)
{
return (*reinterpret_cast<recursive_wrapper<T> const*>(&data)).get();
}
else
{
throw std::runtime_error("in get<T>()");
}
}
VARIANT_INLINE std::size_t get_type_index() const
{
return type_index;
Expand Down Expand Up @@ -738,13 +771,13 @@ auto VARIANT_INLINE static apply_visitor(F f, V & v0, V & v1) -> decltype(V::bin

// getter interface
template<typename ResultType, typename T>
ResultType & get(T & var)
ResultType & get(T & var)
{
return var.template get<ResultType>();
}

template<typename ResultType, typename T>
ResultType const& get(T const& var)
ResultType const& get(T const& var)
{
return var.template get<ResultType>();
}
Expand Down

0 comments on commit 36f1e12

Please sign in to comment.