# Basic Usage

A discriminated union container on some set of types is defined by instantiating the ``boost::variant`` class template with the desired types. These types are called bounded types and are subject to the requirements of the BoundedType concept. Any number of bounded types may be specified, up to some implementation-defined limit (see `BOOST_VARIANT_LIMIT_TYPES`).

For example, the following declares a discriminated union container on `int` and `std::string`:

    boost::variant< int, std::string > v;

By default, a `variant` default-constructs its first bounded type, so `v` initially contains `int(0)`. If this is not desired, or if the first bounded type is not default-constructible, a `variant` can be constructed directly from any value convertible to one of its bounded types. Similarly, a `variant` can be assigned any value convertible to one of its bounded types, as demonstrated in the following:

    v = "hello";

Now `v` contains a `std::string` equal to `"hello"`. We can demonstrate this by streaming `v` to standard output:

    std::cout << v << std::endl;

Usually though, we would like to do more with the content of a `variant` than streaming. Thus, we need some way to access the contained value. There are two ways to accomplish this: `apply_visitor`, which is safest and very powerful, and `get<T>`, which is sometimes more convenient to use.

For instance, suppose we wanted to concatenate to the string contained in `v`. With value retrieval by `get`, this may be accomplished quite simply, as seen in the following:

    std::string& str = boost::get<std::string>(v);
    str += " world! ";

As desired, the `std::string` contained by `v` now is equal to `"hello world! "`. Again, we can demonstrate this by streaming `v` to standard output:

    std::cout << v << std::endl;

While use of `get` is perfectly acceptable in this trivial example, `get` generally suffers from several significant shortcomings. For instance, if we were to write a function accepting a `variant<int, std::string>`, we would not know whether the passed `variant` contained an `int` or a `std::string`. If we insisted upon continued use of `get`, we would need to query the `variant` for its contained type. The following function, which "doubles" the content of the given `variant`, demonstrates this approach:

    void times_two( boost::variant< int, std::string > & operand )
    {
        if ( int* pi = boost::get<int>( &operand ) )
            *pi *= 2;
        else if ( std::string* pstr = boost::get<std::string>( &operand ) )
            *pstr += *pstr;
    }

However, such code is quite brittle, and without careful attention will likely lead to the introduction of subtle logical errors detectable only at runtime. For instance, consider if we wished to extend `times_two` to operate on a `variant` with additional bounded types. Specifically, let's add `std::complex<double>` to the set. Clearly, we would need to at least change the function declaration:

    void times_two( boost::variant< int, std::string, std::complex<double> > & operand )
    {
        // as above...?
    }

Of course, additional changes are required, for currently if the passed `variant` in fact contained a `std::complex` value, `times_two` would silently return -- without any of the desired side-effects and without any error. In this case, the fix is obvious. But in more complicated programs, it could take considerable time to identify and locate the error in the first place.

Thus, real-world use of `variant` typically demands an access mechanism more robust than `get`. For this reason, `variant` supports compile-time checked visitation via `apply_visitor`. Visitation requires that the programmer explicitly handle (or ignore) each bounded type. Failure to do so results in a compile-time error.

Visitation of a `variant` requires a visitor object. The following demonstrates one such implementation of a visitor implementating behavior identical to `times_two`:

    class times_two_visitor
        : public boost::static_visitor<>
    {
    public:

        void operator()(int & i) const
        {
            i *= 2;
        }

        void operator()(std::string & str) const
        {
            str += str;
        }

    };

With the implementation of the above visitor, we can then apply it to `v`, as seen in the following:

    boost::apply_visitor( times_two_visitor(), v );

As expected, the content of `v` is now a `std::string` equal to `"hello world! hello world! "`. (We'll skip the verification this time.)

In addition to enhanced robustness, visitation provides another important advantage over `get`: the ability to write generic visitors. For instance, the following visitor will "double" the content of any `variant` (provided its bounded types each support operator+=):

    class times_two_generic
        : public boost::static_visitor<>
    {
    public:

        template <typename T>
        void operator()( T & operand ) const
        {
            operand += operand;
        }

    };

Again, `apply_visitor` sets the wheels in motion:

    boost::apply_visitor( times_two_generic(), v );

While the initial setup costs of visitation may exceed that required for `get`, the benefits quickly become significant. Before concluding this section, we should explore one last benefit of visitation with `apply_visitor`: delayed visitation. Namely, a special form of `apply_visitor` is available that does not immediately apply the given visitor to any `variant` but rather returns a function object that operates on any `variant` given to it. This behavior is particularly useful when operating on sequences of `variant` type, as the following demonstrates:

    std::vector< boost::variant<int, std::string> > vec;
    vec.push_back( 21 );
    vec.push_back( "hello " );

    times_two_generic visitor;
    std::for_each(
          vec.begin(), vec.end()
       , boost::apply_visitor(visitor)
       );