Question

I am confusing the following problem by identifying the a specific type within boost::variant and pass it as member function argument within a class object. Consider the following code

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);

}

I thought sure about implementing a visitation class/structure (apply_visitor ) within class test. However I got stuck by calling a outer member function namely func3(string s) from the overloaded operator implemented in the visitor class.

Was it helpful?

Solution

The visitor pattern reification will make the compiler do the type-checking for you. All you need to do is tell the compiler what to do when a string is in the Variant:

(check out the example at 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
};

and use boost::apply_visitor to choose the correct function:

int main ()
{
  test t;
  my_dispatcher dispatcher(&t);

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

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

The my_dispatcher(&t) will create an object of your static_visitor implementation, that will be used by the apply_visitor magic.

Hope that's what your were looking fore, since your question wasn't really clear.

Note: alternatively, you derive your test from static_visitor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top