I have this code:
std::vector<boost::variant<int,float,std::string>> data;
template<typename T> T Get(size_t i)
{
if (i < data.size())
return boost::get<T>(data[i]);
return T();
}
how can I check if get<T>
failed so I can return T()
(without exceptions as it's very costly for performance)?
In general you can't.
If you know the type indices, you can - perhaps - do something brittle with
variant::which
.The sure-fire way would be to write a visitor yourself though. Here's a proof of concept:
See it Live On Coliru with
Printing