Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext

Function get

boost::get — Retrieves a value of a specified type from a given variant.

Synopsis

// In header: <boost/variant/get.hpp>


template<typename U, typename T1, typename T2, ..., typename TN> 
  U * get(variant<T1, T2, ..., TN> * operand);
template<typename U, typename T1, typename T2, ..., typename TN> 
  const U * get(const variant<T1, T2, ..., TN> * operand);
template<typename U, typename T1, typename T2, ..., typename TN> 
  U & get(variant<T1, T2, ..., TN> & operand);
template<typename U, typename T1, typename T2, ..., typename TN> 
  const U & get(const variant<T1, T2, ..., TN> & operand);

Description

The get function allows run-time checked, type-safe retrieval of the content of the given variant. The function succeeds only if the content is of the specified type U, with failure indicated as described below.

Warning: After either operand or its content is destroyed (e.g., when the given variant is assigned a value of different type), the returned reference is invalidated. Thus, significant care and caution must be extended when handling the returned reference.

Notes:

As part of its guarantee of type-safety, get enforces const-correctness. Thus, the specified type U must be const-qualified whenever operand or its content is likewise const-qualified. The converse, however, is not required: that is, the specified type U may be const-qualified even when operand and its content are not.

Returns:

If passed a pointer, get returns a pointer to the value content if it is of the specified type U; otherwise, a null pointer is returned. If passed a reference, get returns a reference to the value content if it is of the specified type U; otherwise, an exception is thrown (see below).

Throws:

Overloads taking a variant pointer will not throw; the overloads taking a variant reference throw bad_get if the content is not of the specified type U.

Rationale:

While visitation via apply_visitor is generally preferred due to its greater safety, get may may be more convenient in some cases due to its straightforward usage.

PrevUpHomeNext