Boost logo

Boost :

From: Oleg Abrosimov (beholder_at_[hidden])
Date: 2006-07-21 00:40:28


In order to obtain a polymorphic behavior with boost::variant and keep a
reference semantic in corresponding visitor I've added the following
constructor to boost::reference_wrapper class:

template<typename T1>
reference_wrapper(reference_wrapper<T1> const& rw): t_(rw.get_pointer()) {}

it can be tested with:

int i = 1;
boost::reference_wrapper<double> = boost::ref(i);

I ask someone to add this functionality to boost::reference_wrapper

Oleg Abrosimov.

This is the code I've tried to make workable (feel free to skip it):

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

class base {
public :
     virtual void print() const {
         std::cout << "base\n";
class child :
     public base {
public :
     void print() const {
         std::cout << "child\n";

class my_visitor :
     public boost::static_visitor<>
     void operator()(base& b) const

     void operator()(int i) const
         std::cout << "int\n";

#include <boost/ref.hpp>

int main()
     child c;

     typedef boost::variant<boost::reference_wrapper<base>, int> var_t;
     var_t v = boost::ref(c);

     boost::apply_visitor( my_visitor(), v ); //prints "child"

     base b;
     v = boost::ref(b);
     boost::apply_visitor( my_visitor(), v ); //prints "base"

     return 0;

Boost list run by bdawes at, gregod at, cpdaniel at, john at