0

Is it possible to store the return value of boost::apply_visitor in the member variable of a class?
I need to get Test::Do function to work, but don't know how.

#include "boost/variant/variant.hpp"
#include "boost/variant/apply_visitor.hpp"

using namespace std;
using namespace boost;

class times_two_generic
    : public boost::static_visitor<>
{
public:

    template <typename T>
    void operator()( T & operand ) const
    {
        operand += operand;
    }

};

class Test
{
public:
   Test(){
      times_two_generic visitor;
      //mAppliedVisitor = apply_visitor(visitor);
   }
   ~Test(){}
   void Do(variant<int, string> &v)
   {
      //mAppliedVisitor(v);   // Is it possible to store the value of apply_visitor 
                           // in mAppliedVisitor only once in the constructor of Test? 
                           // and only call mAppliedVisitor member whenever needed.
   }

private:
   // boost::apply_visitor_delayed_t<times_two_generic> mAppliedVisitor;
};

int main(int argc, char **argv) 
{
    variant<int, string> v = 5;
    times_two_generic visitor;

    cout << v << endl;

    apply_visitor(visitor)(v); // v => 10
    boost::apply_visitor_delayed_t<times_two_generic> appliedVisitor = apply_visitor(visitor);
    appliedVisitor(v); // v => 20

   Test t;
   t.Do(v);

    cout << v << endl;
    return 0;
}
B Faley
  • 17,120
  • 43
  • 133
  • 223
  • 1
    The retun type of your `times_two_generic` visitor is `void`. That is what `apply_visitor` will return. So what do you want to store? – Paul Michalik Mar 10 '13 at 09:56
  • 2
    You can get it to work like [this](http://liveworkspace.org/code/3H22eI$1). The `apply_visitor_delayed_t` is initialised in a member-initialiser-list, and the referenced `times_two_generic` is kept alive for the lifetime of the `apply_visitor_delayed_t`. – Mankarse Mar 10 '13 at 10:05
  • @PaulMichalik: See [boost::apply_visitor_delayed_t](http://www.boost.org/doc/libs/1_53_0/doc/html/boost/apply_visitor_delayed_t.html). – Mankarse Mar 10 '13 at 10:25

0 Answers0