Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 识别变体类型_C++_Boost_Boost Variant - Fatal编程技术网

C++ 识别变体类型

C++ 识别变体类型,c++,boost,boost-variant,C++,Boost,Boost Variant,通过识别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

通过识别
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);

}
typedef boost::variant variant;
类测试{
第1款(备选案文五);
void func2(字符串s);
void func3();
}; 
测试::func1(变量V){
//如何识别此函数体中的V类型?
或者我如何在这个函数中调用apply_访问者。
/*
if(v.type()==字符串)
func2();
else if(v.type()==double)
funct3();
*/
}

int test::func2(){cout访问者模式具体化将使编译器为您执行类型检查。您需要做的只是告诉编译器当
变量中有
字符串时该怎么做:

(查看下面的示例: )

my\u dispatcher(&t)
将创建静态访问者实现的对象,该对象将由
apply\u visitor
magic使用

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


注意:或者,您可以从
静态访问者
派生
测试

我真的不明白您想要的是什么。当然,我知道这个解决方案。但是,它遗漏了我所问的重要部分。特别是,所有函数和成员变量都应该在类测试中实现。问题是如果从my_sispatcher中的类测试中创建新的intance,则无法访问实际需要函数func3(字符串s)的intance窗体要执行…任何想法…@sam:Replace
test t
为指向共享
test
对象的指针。@Mankarse:如何在my_dispatcher中设置指向共享测试对象的指针,因为此时测试对象还没有声明。我如何将其作为参数传递给my_dispatcher。这有意义吗?传递
这个func1
中构造dispatcher时,将
测试
对象编码到
my_dispatcher
的构造函数中。
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
};
int main ()
{
  test t;
  my_dispatcher dispatcher(&t);

  Variant V = 3;
  boost::apply_visitor( dispatcher, v );

  V = "hello"; 
  boost::apply_visitor( dispatcher, v );    
}