Reputation: 49
as the title is pretty explanatory, how is the best way to iterate over a boost::variant<std::vector<int>, std::vector<string>>
variable?
Say that I have a structure:
struct foobar{
enum typeOfVariant {intVariant, StringVariant}
boost::variant<std::vector<int>, std::vector<String>> variable;
}
That i receive at a certain point with the guarantee that the enum is corelated with the type from the variant.
To achieve maybe something like:
boost::variant<std::vector<int>, std::vector<string>> var;
for (auto t in var)
{
//do something
}
^this might be the ideal way.
Or to force conversion to a std::vector<int>
or std::vector<string>
, based on the enum type?
Upvotes: 1
Views: 1044
Reputation: 275260
In C++14:
apply_visitor( var, [&](auto&& var){
for( auto&& t : var ) {
// code goes here
}
});
There is no need for the enum
. Variants know what type they have within themselves.
A variant
is a union and an index into the correct type in the union. that index is basically your enum
.
We can do it externally with an if
block and two versions each of which assumes the content is one type or another, or similar, but that adds bulk, and rarely adds value.
Most nominally C++11 compilers can handle the above. Without it you have to either write a function object class manually that replicates it, or you could use the "conditional cast"s and write the loop twice, one for each type.
What can I say, C++14 solved problems.
Upvotes: 1