sohel14_cse_ju
sohel14_cse_ju

Reputation: 2521

How to convert VARIANT to integer

I am converting VARIANT to int using boost::lexical_cast as below :

component.m_id= boost::lexical_cast<int>(id.intVal);

But looks like i am getting garbage value here : id.intVal. What am i doing wrong here ?

Upvotes: 0

Views: 2055

Answers (2)

Venom
Venom

Reputation: 1060

you can use boost::get. But not for casting. It is for extracting the real type from the boost::variant. Example : suppose you have :

boost::variant<bool, int, double> v myVariant;
myVariant = true;

you have to use :

bool value = boost::get<bool>(myVariant);

and not

double value = boost::get<double>(myVariant);

otherwise it will crashes.

Once you have the value you can cast it.

If you don't know the type you set on you boost variant, you have to use : boost::apply_visitor<> like in the example in the link below, at the end of the page :

http://www.boost.org/doc/libs/1_61_0/doc/html/variant.html

but that means you have to do it for each type in your boost::variant

Upvotes: 0

Simon Mourier
Simon Mourier

Reputation: 138950

If you don't really know the type of what the variant holds (in your example, it seems to be a string represented as a VT_BSTR), the best and safest way is to call the Windows API VariantChangeType (or VariantChangeTypeEx is localization is an issue); here is an example (not boost-specific):

VARIANT vIn;
VariantInit(&vIn);
vIn.vt = VT_BSTR;
vIn.bstrVal = ::SysAllocString(L"12345678");

VARIANT vOut;
VariantInit(&vOut);

// convert the input variant into a 32-bit integer
// this works also for other compatible types, not only BSTR
if (S_OK == VariantChangeType(&vOut, &vIn, 0, VT_I4))
{
    // now, you can safely use the intVal member
    printf("out int: %i\n", vOut.intVal);
}    

VariantClear(&vOut);
VariantClear(&vIn);

Upvotes: 2

Related Questions