【发布时间】:2015-01-03 13:02:10
【问题描述】:
我正在尝试从 boost::variant 中获取 int 值。代码生成分段错误 - 为什么? 我将 cmets 放入代码中,这些代码行会产生错误。我以为
int numberInt = boost::get<int>(v);
无法正常工作,所以我将其更改为
int *ptrInt = boost::get<int>(&v);
哪个正在编译,但我仍然无法获得 int 值?与 double 完全相同。字符串类型有效。
#include <iostream>
#include "boost/variant.hpp"
#include <boost/variant/get.hpp>
using namespace std;
int main(int argc, char* argv[])
{
boost::variant<int, double, std::string> v;
v = 16;
v = 3.1415;
v = "hello new year";
//int numberInt = boost::get<int>(v); //1) not working
//double numberDouble = boost::get<double>(v);//2) not working
int *ptrInt = boost::get<int>(&v); //3) compiling
if(ptrInt)
cout << *ptrInt << endl; //4) not displayed
//cout << *ptrInt << endl; //5) segmentation fault
double *ptrDouble = boost::get<double>(&v); //6) compiling
if(ptrDouble)
cout << *ptrDouble << endl; //7) not displayed
//cout << *ptrDouble << endl; //8) segmentation fault
std::string caption = boost::get<string>(v);
cout << caption << endl; //9) working
return 0;
}
// clear && clear && g++ test.cpp -std=c++11 -o test && ./test
【问题讨论】:
标签: c++ boost get int boost-variant