我想使用 aboost.variant<T0,T1,T2>
作为模板“访问者”类的参数,该类将根据 boost.variant 访问者机制的要求提供访问者运算符,在这种情况下,所有返回 void 即,
void operator()(T0 value);
void operator()(T1 value);
void operator()(T2 value);
该模板还将为每个类型 T0... 在变体中具有相应的虚函数,默认情况下该虚函数不执行任何操作。用户可以从模板类继承并只重新定义他感兴趣的那些虚函数。这类似于众所周知的“模板方法”模式。我能想出的唯一解决方案是将 boost::variant 和关联的访问者包装在一个模板中,并通过 typedefs 访问它们。这工作正常,但感觉有点笨拙。这是代码:
#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)
{
Process(value);
}
void operator()(T1 value)
{
Process(value);
}
void operator()(T2 value)
{
Process(value);
}
virtual void Process(T0 val){/*do nothing */}
virtual void Process(T1 val){/*do nothing */}
virtual void Process(T2 val){/*do nothing */}
protected:
Visitor(){}
};
typedef Visitor VisitorType;
private:
VariantWrapper(){}
};
然后按如下方式使用该类:
typedef VariantWapper<bool,int,double> VariantWrapperType;
typedef VariantWrapperType::VariantType VariantType;
typedef VariantWrapperType::VisitorType VisitorType;
struct Visitor : public VisitorType
{
void Process(bool val){/*do something*/}
void Process(int val){/*do something*/}
/* this class is not interested in the double value */
};
VariantType data(true);
apply_visitor(Visitor(),data);
正如我所说,这似乎工作得很好,但如果我不必创建一个特殊的包装类来将变体和访问者联系在一起,我会更喜欢它。我希望能够直接使用 boost.variant 来实例化模板访问者类。我看过使用类型参数、非类型参数和模板模板参数,但似乎没有任何建议。我想做的事是不可能的吗?我可能会遗漏一些东西,如果有人对此有任何意见,我将不胜感激。