I feel like I’m having a serious ‘Doh!’ moment here…
I’m currently trying to implement:
std::ostream& operator<<(std::ostream &out, const MyType &type)
Where MyType holds a boost::variant of int, char and bool. IE: Make my variant streamable.
I tried doing this:
out << boost::apply_visitor(MyTypePrintVisitor(), type);
return out;
And MyTypePrintVisitor has a templated function that uses boost::lexical_cast to convert the int, char or bool to a string.
However, this doesn’t compile, with the error that apply_visitor is not a function of MyType.
I then did this:
if(type.variant.type() == int)
out << boost::get<int> (type.variant);
// So on for char and bool
...
Is there a more elegant solution I’m missing?
Thanks.
Edit: Problem solved. See the first solution and my comment to that.
You should be able to stream a
variantif all its contained types are streamable. Demonstration:Output:
If you do need to use a visitor (perhaps because some of the contained types aren’t streamable), then you need to apply it to the
variantitself; your snippet of code looks like it’s applying it to aMyTypeobject instead.