小编Tom*_*dan的帖子

boost :: variant的访客模板

我想用一个boost.variant<T0,T1,T2>作为参数传递到模板"访问者"类,它会为游客提供运营商所要求的boost.variant游客机制,在这种情况下,所有返回void即

void operator()(T0 value);
void operator()(T1 value);
void operator()(T2 value);
Run Code Online (Sandbox Code Playgroud)

该模板还将为变体中的每个类型T0 ...具有相应的虚函数,该函数默认不执行任何操作.用户可以从模板类继承并仅重新定义他感兴趣的虚拟函数.这类似于众所周知的"模板方法"模式.我能够想出的唯一解决方案是将boost :: variant和关联的访问者包装在一个模板中,并通过typedef访问它们.这没关系,但感觉有点笨重.这是代码:

#include "boost/variant.hpp"

//create specializations of VariantWrapper for different numbers of variants - 
//just show a template for a variant with three types here. 
//variadic template parameter list would be even better! 

template<typename T0, typename T1, typename T2>
struct VariantWrapper
{
    //the type for the variant
    typedef boost::variant<T0,T1,T2> VariantType;

    //The visitor class for this variant
    struct Visitor : public boost::static_visitor<>
    {
        void operator()(T0 value)
        { …
Run Code Online (Sandbox Code Playgroud)

c++ templates boost variant boost-variant

10
推荐指数
1
解决办法
1万
查看次数

标签 统计

boost ×1

boost-variant ×1

c++ ×1

templates ×1

variant ×1