Boost logo

Boost Users :

From: Yuval Ronen (ronen_yuval_at_[hidden])
Date: 2007-03-01 14:58:13


Digvijoy Chatterjee wrote:
> Hi,
>
> i have a boost::variant holding some C++ types which have to be inserted
> into the database :
>
> boost::variant<int, std::string, double > dbColumnValueVar;
>
> before i insert the value_type into the database
> I need to call a processing function which is overloaded for every
> datatype used in the variant
> ie. each of these functions are defined
>
> process ( int );
> process ( std::string );
> process ( double);
> template <class T> process(T);
> .....
>
> what i do not understand is how do i use apply_visitor or some other
> tactic to automatically dispatch the call to the right process function
> as in :
>
> boost::variant<int, std::string, double > dbColumnVar;
> dbColumnVar = "hello world";
> process ( dbColumnVar ); // should call process std::string ....but is
> always calling the generic template version ??
> dbColumnVar = 1.3434;
> process ( dbColumnVar ); //again calls generic template not specialization

struct process_visitor : boost::static_visitor<void>
{
     template <typename T>
     void operator()([const] T &val) { process(val); }
};

process_visitor pv;
dbColumnVar.apply_visitor(pv);

> cout << dbColumnVar
> is somehow able to get the correct overloaded << operator for the
> hidden datatype
> irrespective of datatype ??

boost::variant has an operator<< overload which calls an internal
visitor (as in the previous example) to call the stored type's operator<<.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net