c++enumsprotocol-buffersprotobuf-c

How to get the next enum value from an enum in protobuf?


I have a protobuf message with non-consecutive enum values something like this:

message Information {
    enum Versions {
        version1 = 0;
        version2 = 1;
        version3 = 10;
        version4 = 20;   
        version5 = 30;    
    }
}

I want to have a C++ function GetNextVersion() which takes in one enum version and gives the next version as output. For eg: GetNextVersion(Information::version4) should give Information::version5 as output. Is there any inbuilt and easy method to do this?


Solution

  • You can use protobuf's reflection to achieve the goal:

    Information::Versions GetNextVersion(Information::Versions ver) {
        const auto *desc = Information::Versions_descriptor();
        auto cur_idx = desc->FindValueByNumber(ver)->index();
        if (cur_idx >= desc->value_count() - 1) {
            throw runtime_error("no next enum");
        }
    
        auto next_idx = cur_idx + 1;
        return Information::Versions(desc->value(next_idx)->number());
    }
    
    int main() {
        try {
            auto ver = Information::version1;
            while (true) {
                cout << ver << endl;
                ver = GetNextVersion(ver);
            }
        } catch (const runtime_error &e) {
            cout << e.what() << endl;
        }
        return 0;
    }