$include_dir="/home/hyper-archives/boost-users/include"; include("$include_dir/msg-header.inc") ?>
Subject: Re: [Boost-users] boost::variant usage question
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2009-06-24 16:50:32
AMDG
Zachary Turner wrote:
> Suppose I've got a bunch of different classes that all support a
> common compile-time interface.  In other words, a bunch of different
> classes, each of which has N methods with identical names and
> signatures but no common base class.
>
> I want to make a variant out of all these types, and in addition I
> want to allow visititation to all of the common methods.
>
> Currently I have defined a separate static_visitor derived class for
> every common method, but this is a little bit annoying.  For example,
> I have currently something like this:
>
> struct Foo1
> {
>     void f(int);
>     void g(double);
>     void h(string);
> };
>
> struct Foo2
> {
>     void f(int);         //Common method
>     void g(double);  //Common method
>     void h(float);     //Not a common method
> };
>
> struct visit_f : public boost::static_visitor<>
> {
>     template<typename T>
>     void operator()(T& t, int i) const
>     {
>         t.f(i);
>     }
> };
>
> struct visit_g : public boost::static_visitor<>
> {
>    template<typename T>
>    void operator()(T& t, double d) const
>    {
>        t.g(d);
>    }
> };
>
>
> What would be the suggested way of making this more generic, so that I
> need not have a separate visitor for every method?
>   
I don't think that there's a good way except to
use a macro.
#define FORWARDING_VISITOR(function) \
struct visit_ ## function : public boost::static_visitor<>\
{\
    template<class T0, class T1>\
    void operator()(T0& t0, T1& t1) const {\
        t0.function(t1);\
    }\
}
FORWARDING_VISITOR(f);
FORWARDING_VISITOR(g);
In Christ,
Steven Watanabe