我试图在类对象中识别boost :: variant的类型以执行关联的成员函数。请考虑以下代码:
#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);
}
问题是我需要在成员函数中识别Variant的类型,以便在同一对象中调用该数据类型EVEN的相关成员函数。
答案 0 :(得分:3)
问题不是很清楚,但你是否也在寻找这个?
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);
}
编辑已向const
添加operator()
限定符,以允许在my_visitor
中使用apply_visitor()
的临时值。