boost::variant 获取最后访问的类型
这就是我想要做的:
boost::variant a<int, string>;
int b;
a=4;
b=a; //doesn't work. What is the easiest way to make b=4?
我知道我可以使用 get,但我希望能够在不指定类型的情况下执行此操作。我可以使用 apply_visitor 和访问者对象来完成此操作,但我想知道是否有更简单的方法。
This is what I want to do:
boost::variant a<int, string>;
int b;
a=4;
b=a; //doesn't work. What is the easiest way to make b=4?
I know I can use get, but I want to be able to do this without specifying the type. I can do it with apply_visitor and a visitor object, but I was wondering if there is a simpler way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您有支持 C++0x 的编译器,则可以使用令人惊叹的
decltype
:我不知道您为什么要这样做,因为您已经知道类型。
If you have a compiler that supports C++0x, you can use the amazing
decltype
:I don't know why you'd want to do this though since you already know the type.
您可以编写一个辅助函数:
但说真的,我认为这比它给您带来的代价更多。
You could write a helper function:
But seriously, I think this costs you more than it buys you.
没有。
您可以调用
variant<>::which()
来获取variant<>
当前初始化类型或variant<> 的索引: :type()
获取当前初始化类型的std::type_info
,但除此之外无法提取当前初始化类型的值get<>
和apply_visitor
。Nope.
You can call
variant<>::which()
to get the index of thevariant<>
's currently initialized type orvariant<>::type()
to get thestd::type_info
for the currently initialized type, but there's no way to extract the value of the currently initialized type other thanget<>
andapply_visitor
.