Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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
}

boost::variant (please don't capitalize 'v') works another way: you can only get back what you put inside. Think about it as a type-safe(r) union.

Checking documenation and tutorial also won't hurt.

Boost.Any library doesn't differ from Boost.Variant in this respect (what you put is what you get :) ), but boost::any is unbounded: you can store value of any type in boost::any, but in boost::variant you can only store what was declared by variant's template parameters.

boost::variant does not do conversion for you. There are other separate means to convert a string to an integer, such as strtol(), sscanf(), boost::lexical_cast<>()...

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