boost::variant get last accessed type
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.
If you have a compiler that supports C++0x, you can use the amazing decltype
:
boost::variant a<int, string>;
int b;
a = 4;
b = boost::get<decltype(b)>(a);
I don't know why you'd want to do this though since you already know the type.
You could write a helper function:
template <class V, typename T>
copy_variant(const V& v, T& t) { t = get<T>(v); }
// ...
copy_variant(a, b);
But seriously, I think this costs you more than it buys you.
Nope.
You can call variant<>::which()
to get the index of the variant<>
's currently initialized type or variant<>::type()
to get the std::type_info
for the currently initialized type, but there's no way to extract the value of the currently initialized type other than get<>
and apply_visitor
.
精彩评论