Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Substituting `std::holds_alternative` in C++14 with mapbox variant

I’m currently downporting C++17 code to C++14. Since C++14 doesn’t have variant I’m using the variant implementation by mapbox which is available here. Basically, substituting variant using mapbox::util::variant works fine but apparently mapbox’s implementation of variant doesn’t have an equivalent for std::holds_alternative which is unavailable in C++14. So I don’t know how to port the following code to C++14:

bool isType() const
{
    return std::holds_alternative<SheetType>(m_sheet);
}

m_sheet is declared like this:

mapbox::util::variant<XLWorksheet, XLChartsheet> m_sheet;

Does anybody have an idea how to do what std::holds_alternative does in C++14 with mapbox’s variant implementation? Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There’s a mapbox::util::variant::is member template. In non-template code you’d replace

return std::holds_alternative<SheetType>(m_sheet);

by

return m_sheet.is<SheetType>();

Whereas in templates, if SheetType is dependent, then you’d need

return m_sheet.template is<SheetType>();

Which is why std::holds_alteantive, std::get, and co. are implemented as free functions. If need be, it’s not hard to wrap is either:

template<typename Alt, typename ...Vars>
bool mapbox_holds_alternative(mapbox::util::variant<Vars...> const& v) {
    return v.template is<Alt>();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading