c++c++14std-variant

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!


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>();
    }