调用boost :: variant中类型的通用方法

the*_*use 6 c++ generic-programming visitor-pattern boost-variant

如果我boost::variant支持的所有类型都使用相同的方法,那么有没有办法一般地调用它(即不为每个方法单独调用它static_visitor)?

我正试图让这样的东西起作用:

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();
}
Run Code Online (Sandbox Code Playgroud)

但它无法编译说'boo' : is not a member of 'boost::variant<T0_,T1,T2>'.

目前,我有一些类都继承自接口,因此可以多态地使用它们的单个共享方法.我还希望能够通过访问者使用这些类,因为所有其他方法对于每个具体类都是唯一的.我希望boost::variant可能是在这里实现我自己的访问者机制的更好的替代方案.是吗?

Mic*_*son 4

没有直接的方法,但您可以使用模板使 static_visitor 变得非常简洁。

从 boost 文档修改:

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

现在你可以这样做:

boost::apply_visitor( boo_generic(), v );
Run Code Online (Sandbox Code Playgroud)

事实上,您可以将其概括为获取基类的函数指针:

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

然后你可以这样做:

boost::apply_visitor( boo_generic( IBase::boo ), v );
Run Code Online (Sandbox Code Playgroud)

或者类似的东西 - 我的函数指针语法可能是错误的,但希望你能明白。