Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::variant usage

I am developing GUI application via wxWidgets. It has 2 parts: GUI part and "Logic" part. I want to have Logic part totally independent on wxWidgets. But one component in the GUI returning wxVariant and I need to use it in the Logic part.

So I am looking for a way to "convert" wxVariant to boost::variant

wxVariant works like this:

wxVariant v("37");
int i = v.GetInteger(); //i==37

So I am thinking something like

string s = methodReturningWxVariant().GetString();
boost::variant bV(s);

//later in code e.g
bV.GetInt();
bV.GetBool();

Is it possible to use boost::Variant (or boost::Any) like this?

like image 815
relaxxx Avatar asked Mar 28 '11 14:03

relaxxx


2 Answers

Simple answer? No. You cannot convert via strings, this induces a loss of information and boost::variant does not automatically attempt to parse strings.

I don’t know whether wxVariant offers an explicit conversion – in general, it may be difficult to convert to boost::variant without testing for special cases.

like image 25
Konrad Rudolph Avatar answered Oct 19 '22 23:10

Konrad Rudolph


You can probably use boost::variant with some changes. To start with, you need to tell boost::variant which types it will be storing:

boost::variant<int, string, bool> v;

Since you probably will be using this type in a few places, you will probably want to create an alias for it. i.e.

typedef boost::variant<int, string, bool> myvar;

then you can use myvar directly:

myvar x = "hello";
myvar y = 20;
myvar z = false;

to retrieve values:

string s = boost::get<string>(x);
int i = boost::get<int>(y);
bool b = boost::get<bool>(z);

If you attempt to get a different type than is stored in the variant, it will throw an exception.

You can query the variant's type with the which() member function. It will return a 0-based index to the type the variant is currently holding.

switch (x.which()) {
case 0: // it's an int
case 1: // it's a string
case 2: // it's a bool
}
like image 115
Ferruccio Avatar answered Oct 20 '22 00:10

Ferruccio