|
Boost Users : |
From: Yuval Ronen (ronen_yuval_at_[hidden])
Date: 2007-01-19 05:40:39
cdr_at_[hidden] wrote:
> Hello,
>
> Why does boost::apply_visitor take a const reference to the visitor object? This forces me to write a
> boost::static_visitor-derived visitor that looks like this:
>
> class my_visitor_t : public boost::static_visitor<>
> {
> template <typename T> void operator()(T const& t) const
> { // do something ... }
>
> };
>
> ... when what I would really like to do is something like this:
>
> class my_visitor_t : public boost::static_visitor<>
> {
> my_visitor(my_data & _data) : data(_data) {}
>
> void operator()(int const& i) // NOT const
> { // data.blah.blah = // blah }
>
> template <typename T> void operator()(T const& t) // NOT const
> { // data.foo() }
>
> my_data & data
>
> };
>
> So I might have several different instances of a given a my_variant_t:
>
> my_variant_t v1;
> my_variant_t v2;
> my_variant_t v3;
>
> my_data_t my_data;
>
> my_visitor_t my_visitor(my_data);
>
> boost::apply_visitor(my_visitor, v1);
> boost::apply_visitor(my_visitor, v2);
> // and so on...
>
> ... BUT, the fact that I must make the visitor operator() const makes this impossible and is inconsistent with the way that I'm
> used to leveraging visitors in the BGL. Would someone be kind enough to comment on the rationale behind this? What am I missing
> here?
>
> - Thanks
>
> Chris
Accepting the visitor by non-const reference will make calling
apply_visitor with a temporary visitor not compile, so there's a
downside to that too. You can use the apply_visitor member function of
variant:
v1.apply_visitor(my_visitor);
v2.apply_visitor(my_visitor);
which accepts the visitor by non-const reference.
Not that I'm saying that any if these solutions is best. IMO, a
static_visitor is some kind of a functor, and as such should be accepted
by value, making it possible to pass temporaries, and write code as you
described. However, I couldn't convince about it...
Yuval
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