Question

I am trying to identify the type of a boost::variant within a class object to perform the associated member functions. Consider the following code:

#include <cstdio>
#include <cassert>
#include <iostream>
#include <boost/variant.hpp>
#include <string>
using namespace std;

typedef boost::variant< string, double> Variant;

class test{ 
  public:
    void func1 (Variant V); 
    void func2 (string s); 
    void func3 (double d);
    struct my_visitor : public boost::static_visitor<> {
      test &my_test;
      my_visitor(test &arg) : my_test(arg) {}

      void operator()( string s ) { my_test.func2(s); }
      void operator()( double d ) { my_test.func3(d); }
      //... for each supported type
    };

}; 


void test::func1(Variant V){
  boost::apply_visitor( my_visitor(*this),V);
}

void test::func2( string s){ cout << "func3" << endl;}
void test::func3(double d){ cout << "func4" << endl;}

int main (){
    test t;
    Variant V = 3.1;
    t.func1(V); 
    V = "hello"; 
    t.func1(V);
}

The issue is I need to identify the type of Variant within a member function to call the related member function for that data type EVEN within the same object.

Was it helpful?

Solution

The question is not quite clear, but are you perhaps looking for this?

class test {
  //...

struct my_visitor : public boost::static_visitor<> {
  test &my_test;
  my_visitor(test &arg) : my_test(arg) {}

  void operator()( string s ) const { my_test.func3(s); }
  void operator()( double d ) const { my_test.func4(d); }
  //... for each supported type
};

  //...
};


test::func1(Variant V) {
  boost::apply_visitor(my_visitor(*this), V);
}

EDIT Added const qualifiers to operator() to allow using temporaries of my_visitor in apply_visitor().

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