Call methods common to types in boost :: variant

If all types in my boost::variant support the same method, is there a way to call it as a whole (i.e. do not call it separately for each static_visitor method)?

I am trying to get something like this to work:

 class A { void boo() {} }; class B { void boo() {} }; class C { void boo() {} }; typedef boost::variant<A, B, C> X; void foo(X& d) { x.boo(); } 

but he will not compile the statement 'boo' : is not a member of 'boost::variant<T0_,T1,T2>' .

I currently have some classes inherited from the interface, so their one common method can be used polymorphically. I also want to be able to use classes through the visitor, since all other methods are unique to each particular class. I was hoping that boost::variant might be the best alternative to implementing my own visitor mechanism here. It?

+6
source share
1 answer

There is no direct way, but you can make static_visitor pretty short with templates.

Changed from promotion docs:

 struct boo_generic : public boost::static_visitor<> { template <typename T> void operator()( T & operand ) const { operand.boo(); } }; 

Now you can do this:

 boost::apply_visitor( boo_generic(), v ); 

Infact you can generalize this to take a pointer to a function of your base class:

 struct fn_generic : public boost::static_visitor<> { fn_generic( void (IBase::fn)() ) : fn_(fn) {} template<T> void operator() ( T & op ) const { op.*fn(); } } 

Then you can do:

 boost::apply_visitor( boo_generic( IBase::boo ), v ); 

Or something like that - I probably misunderstood the syntax of a function pointer, but I hope you understand this idea.

+4
source

Source: https://habr.com/ru/post/918523/


All Articles