ank*_*h13 2 c++ boost boost-variant
我们可以明确地对可以存储在boost varaint中的值进行类型转换吗?
例:
typedef int abc;
typedef int asd;
typedef boost::variant<abc, char, asd, float> link_try1;
int main()
{
link_try1 qw;
qw = static_cast<asd>(1234);
printf("value of which is:%d", qw.which());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在这里,我希望which()函数重新启动3但它总是重新生成0.有没有办法直接更改其中的值_(类变量中的私有变量)或显式指定要使用的数据类型?
关心Ankith
这是可能的,但它不会按预期工作.
关于变体的关键思想是类型充当关键.当您实际请求给定类型(使用boost::get或访问)时,variant匹配键的第一个类型被选中,因此这里asd将被傲慢地忽略.
如果你需要为不同的目的存储几个整数,你可以BOOST_STRONG_TYPEDEF用来创建不同的类整数类并使用它们variant.