我们可以显式转换要存储在 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;
}
这里我希望 which() 函数重新运行 3,但它总是重新运行 0。 有没有一种方法可以直接更改 which_ 中的值(类变体中的私有(private)变量)或显式指定要使用的数据类型??
问候 安基斯
最佳答案
这是可能的,但它不会按预期工作。
变体的关键思想是类型充当键。当您实际请求给定类型时(使用 boost::get
或访问),variant
中与键匹配的第一个类型被选中,因此此处 asd
会被傲慢地忽略。
如果您需要为不同的目的存储多个整数,您可以使用 BOOST_STRONG_TYPEDEF
创建不同的类整数类并在 variant
中使用它们。
关于c++ - 在 boost 变体中使用相同的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5814412/