Question

I have a use case where I'd like to process the element contained within a boost::variant without regard to its type.

Is there a way to get a pointer to the variant's data without knowing the element's type?

Was it helpful?

Solution

You can write a visitor to do it:

 typedef boost::variant<T1,T2,T3> my_variant;
 void foo(my_variant v) {
      struct get_pointer: boost::static_visitor<void *> {
          template<class T>
          void *operator()(T &element) const 
          {
            return &element 
          }
      };
      get_pointer vis;
      void *data = boost::apply_visitor(vis, v);
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top