Program Listing for File EnumWrapper.hpp

Return to documentation for file (src/include/EnumWrapper.hpp)

#ifndef ENUMWRAPPER_HPP
#define ENUMWRAPPER_HPP

#include <boost/program_options.hpp>
#include <map>
#include <string>

// A helper class to make configuring enums easier with boost::program_options.

namespace EnumWrap {
template <typename E> class EnumWrapper;
template <typename E> std::istream& operator>>(std::istream&, EnumWrapper<E>&);

template <typename E> class EnumWrapper {
public:
    typedef std::map<std::string, E> MapType;

    E operator()(const std::string& key)
    {
        value = map.at(key);
        return value;
    }
    operator E() const { return value; }

    static void setMap(const MapType& inMap)
    {
        map.clear();
        map = inMap;
    }

    friend std::istream& operator>><E>(std::istream& is, EnumWrapper<E>&);

private:
    static MapType map;

    E value;
};

template <typename E> typename EnumWrapper<E>::MapType EnumWrapper<E>::map;

template <typename E> std::istream& operator>>(std::istream& is, EnumWrapper<E>& e)
{
    std::string tok;
    is >> tok;
    try {
        e(tok);
    } catch (const std::out_of_range& oor) {
        throw boost::program_options::validation_error(
            boost::program_options::validation_error::invalid_option);
    }
    return is;
}
}

#endif // ndef ENUMWRAPPER_HPP