boost::variant usage

relaxxx picture relaxxx · Mar 28, 2011 · Viewed 20.9k times · Source

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?

Answer

Ferruccio picture Ferruccio · Mar 28, 2011

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
}