C++ Boost::variant::variant














































C++ Boost::variant::variant



DESCRIPTION:

The variant class template is a safe, generic, stack-baeased discriminated union container, offering a simple solution for manipulating an object from a heterogeneous set of types in a uniform manner. Whereas standard containers such as std::vector may be thought of as "multi-value, single type," variant is "multi-type, single value."


features of boost::variant :


header: 

#include<"boost/variant.hpp



Implementaion:


#include "boost/variant.hpp"
#include <iostream>

class my_visitor : public boost::static_visitor<int>
{
         public:
         int operator()(int i) const
       {
         return i;
        }
         int operator()(const std::string & str) const
       {
        return str.length();
      }
};

    int main( )
{
                 boost::variant< int, std::string > u("welcome");
                 std::cout << u; //returns string

                 int result = boost::apply_visitor( my_visitor(), u );
                 std::cout << result;  // returns string length
}

OUTPUT:



Comments