Functions to extract the value from the generalized union type.

From Mechanism to Method
Valued Conversions

Kevlin Henney
Listing 3. Functions to extract the value from the generalized union type.


class any
{
public:
  ...
  operator const void *() const
  {
      return content;
  }
  template<typename value_type>
  bool copy_to(value_type &value) const
  {
      const value_type *copyable =
        to_ptr<value_type>();
      if(copyable)
          value = *copyable;
      return copyable;
  }
  template<typename value_type>
  const value_type *to_ptr() const
  {
      return type_info() == typeid(value_type)
          ? &static_cast<
            holder<value_type> *>(content)->held
          : 0;
  }
  ...
};
template<typename value_type>
value_type any_cast(const any &operand)
{
  const value_type *result =
    operand.to_ptr<value_type>();
  return result ? *result : throw std::bad_cast();
}

Featured

Upcoming Events

AppTrends

Sign up for our newsletter.

I agree to this site's Privacy Policy.