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();
}

Upcoming Training Events

0 AM
Visual Studio Live! San Diego
September 8-12, 2025
Live! 360 Orlando
November 16-21, 2025
Cloud & Containers Live! Orlando
November 16-21, 2025
Data Platform Live! Orlando
November 16-21, 2025
Visual Studio Live! Orlando
November 16-21, 2025