Boost logo

Boost Users :

From: Jeffrey A. Edlund (jedlund_at_[hidden])
Date: 2008-04-09 16:55:54


On Wed, 09 Apr 2008 20:39:26 +0200
Olaf Peter <ope-devel_at_[hidden]> wrote:

> Hi,
>
> I've wrapped a variant<double,bool> into a tuple. Unpacking the tuple
> works as far I can see. I want to print the tuple for doubles with
> one pretty print functor and for booleans with another functor (not
> shown here).
>
> Anyway, variant_print takes a long argument list as the error message
> shows. How can I pass it convinient?

This is the type of your variant. The first two are double and bool,
the rest are placeholders that would be replaced if your variant held
more types.

> I guess, inside the variant_print I have to use the vistor to
> dispatch the print functors, isn't?

That's basically how I'd do it. I've modified your example to demonstrate this:

---8<---
#include <boost/variant.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_io.hpp>
#include <iostream>

typedef boost::variant<double, bool> double_variant;
typedef boost::tuple<double_variant,double_variant> double_tuple;

class output_visitor : public boost::static_visitor<std::ostream&>
{
    std::ostream& os;
public:
    output_visitor(std::ostream& os_):os(os_) {};

    result_type operator()(const double &arg) const
    {
        os << arg;
        return os;
    }

    result_type operator()(const bool & arg) const
    {
        if (arg) {
            os << "TRUE";
        } else {
            os << "FALSE";
        }
        return os;
    }
};

std::ostream& operator<<( std::ostream& os, const double_variant& p )
{
    output_visitor out_v(os);
    boost::apply_visitor(out_v,p);
    return os;
}

std::ostream& operator<<( std::ostream& os, const double_tuple& p )
{
    os << "("<<p.get<0>()<<","<<p.get<1>()<<")";
    return os;
}

int main()
{
     double_tuple v1;
     double_tuple v2;

     v1.get<0>() = 3.14;
     v1.get<1>() = true;

     v2.get<0>() = false;
     v2.get<1>() = 2.718;

     std::cout << v1 << std::endl;
     std::cout << v2 << std::endl;
}

// Output is:
// (3.14,TRUE)
// (FALSE,2.718)

--->8---

Jeffrey


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