我使用boost::lexical_cast将变量转换为整数,如下所示:
component.m_id= boost::lexical_cast<int>(id.intVal);但看起来我在这里得到了垃圾价值: id.intVal。我在这里做错了什么?
发布于 2016-09-18 17:49:27
如果您真的不知道变量包含的类型(在您的示例中,它似乎是一个表示为VT_BSTR的字符串),最好也是最安全的方法是调用Windows API VariantChangeType (或者VariantChangeTypeEx是本地化问题);下面是一个示例(不是boost特定的):
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);发布于 2016-09-18 17:56:28
您可以使用boost::get。但不是为了选角。它用于从boost::variant中提取真正的类型。示例:假设您有:
boost::variant<bool, int, double> v myVariant;
myVariant = true;你必须使用:
bool value = boost::get<bool>(myVariant);而不是
double value = boost::get<double>(myVariant);否则它会崩溃。
一旦你有了值,你就可以对它进行强制转换。
如果您不知道您在boost变量上设置的类型,则必须在页面末尾使用:boost::apply_visitor<>,如以下链接中的示例所示:
http://www.boost.org/doc/libs/1_61_0/doc/html/variant.html
但这意味着您必须为您的boost::variant中的每种类型执行此操作
https://stackoverflow.com/questions/39555784
复制相似问题