Skip to content

add macro for enum types #27

Description

@laroque

At various times it is useful to have a conversion between an enum type and a string (for example, a user-written config file will have the string name which we want to unpack to an enum value). A nice pattern looks like:

file.hh

    enum class op_t:uint32_t {
            set = 0,
            get = 1,
            config = 6, // deprecated as of v2.0.0
            send = 7,
            run = 8,
            cmd = 9,
            unknown = UINT32_MAX
    };

file.cc

    DRIPLINE_API std::string to_string( op_t an_op )
    {
        switch (an_op) {
            case op_t::set: return "set";
            case op_t::get: return "get";
            case op_t::config: return "config";//config is deprecated
            case op_t::send: return "send";
            case op_t::run: return "run";
            case op_t::cmd: return "cmd";
            case op_t::unknown: return "unknown";
            default: throw dripline_error() << "op_t value <" << an_op << "> not recognized";
        }
        //TODO explicitly throw something here?
    }
    DRIPLINE_API op_t to_op_t( std::string an_op_str )
    {
        if ( an_op_str == to_string( op_t::set ) ) return op_t::set;
        if ( an_op_str == to_string( op_t::get ) ) return op_t::get;
        if ( an_op_str == to_string( op_t::config ) ) return op_t::config;
        if ( an_op_str == to_string( op_t::send ) ) return op_t::send;
        if ( an_op_str == to_string( op_t::run ) ) return op_t::run;
        if ( an_op_str == to_string( op_t::cmd ) ) return op_t::cmd;
        if ( an_op_str == to_string( op_t::unknown ) ) return op_t::unknown;
        throw dripline_error() << "unable to map <" << an_op_str << "> to an op_t value";
        //TODO explicitly throw something here?
    }

It would be nice if this were all able to be done in a macro, the amount of logic is large (dealing with entries with and without specified value assignments, variable number of entries, etc.). Also, we have to decide if we are either okay with having the functions in the header, or if there is a way for the macro to also edit the source file, or some other pattern that isn't obvious to me yet.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions