确定变体类型

identify variant type

本文关键字:类型      更新时间:2023-10-16

我通过在boost::variant中识别特定类型并将其作为类对象中的成员函数参数传递来混淆以下问题。请考虑以下代码

typedef boost::variant<int, string, double> Variant;
class test{ 
  void func1 (Variant V); 
  void func2 (string s); 
  void func3 ();

}; 

test::func1(Variant V){
    // How can I identify the type of V inside the body of this function? 
Or how can I call the apply_visitor inside this function.
  /*
  if(v.type() == string) 
    func2(); 
  else if(v.type() == double) 
    funct3(); 
  */
}
int test::func2(){ cout << "func3" << endl;}
int test::func3(){ cout << "func4" << endl;}
...
int main ()
{
  test t;
      Variant V = 3;
      t.func1(V); 
      V = "hello"; 
      t.func1(V);
}

我想确定在类测试中实现访问类/结构(apply_visitor)。但是,我从访问者类中实现的重载运算符调用一个外部成员函数,即func3(字符串s)而陷入困境。

访问者模式重新化将使编译器为您执行类型检查。 您需要做的就是告诉编译器当stringVariant中时该怎么做:

(查看示例http://www.boost.org/doc/libs/1_35_0/doc/html/variant/tutorial.html)

struct my_dispatcher : public boost::static_visitor<> {
    test* t;
    my_dispatcher(test* t): t(t) {}
    void operator()( string s ) { t.func3(s); }
    void operator()( double d ) { t.func4(d); }
    //... for each supported type
};

并使用boost::apply_visitor选择正确的功能:

int main ()
{
  test t;
  my_dispatcher dispatcher(&t);
  Variant V = 3;
  boost::apply_visitor( dispatcher, v );
  V = "hello"; 
  boost::apply_visitor( dispatcher, v );    
}

my_dispatcher(&t)将创建您的static_visitor实现对象,该对象将由apply_visitor魔法使用。

希望这就是你所期待的,因为你的问题不是很清楚。

注意:或者,您可以从static_visitor派生test