4

I want to declare an enum, but I want it to be of size "int8_t" explicitly. As per protbuf docs[1], the generated enum in c++ is a standard c++ enum without explicitly mentioning the underlying type.

i.e. A declaration like this:

enum Foo {
  VALUE_A = 0;
  VALUE_B = 5;
  VALUE_C = 1234;
}

Would generate something like this:

enum Foo {
      VALUE_A = 0;
      VALUE_B = 5;
      VALUE_C = 1234;
      Foo_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min,
      Foo_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max
    }

Is there anyway I can force protobuf to generate the enum with the type explicitly mentioned in the definition? Something like this:

enum Foo : int8_t {
      VALUE_A = 0;
      VALUE_B = 5;
      VALUE_C = 1234;
      Foo_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32min,
      Foo_INT_MIN_SENTINEL_DO_NOT_USE_ = ::google::protobuf::kint32max
    }

Why do I need this?

I want to forward declare my proto enum, and forward declaration of enums need you to:

  1. Mention the datatype (so that compiler can assume the size used by the object)

  2. The declaration of the enum must mention the exact same type as the definition [2]

Any help would be much appreciated.

[1] https://developers.google.com/protocol-buffers/docs/reference/cpp-generated#enum

[2] https://stackoverflow.com/a/42768812/3069919

The-Big-K
  • 2,672
  • 16
  • 35
  • 1
    I'm not sure you can since google protocol buffers supports languages that don't support explicit enum sizing. And within google protocol buffers int size doesn't matter (much) since it's all packed up anyway. **Generally**, it's hard to generate *optimal (for use)* structures with protobufs, which is why people often write constructors/converter classes that do protobufDTO->internal object. – zzxyz Nov 07 '18 at 02:11
  • @zzxyz Does makes sense. In my case, the internal object is also an enum, so I'm pretty much duplicating the protoenum in code, and -ing the ordinals of the 2 enums just to make sure that they are in sync. Thanks for suggestion though. – The-Big-K Nov 07 '18 at 02:14
  • @xaxxon The compiler does not let me forward declare without a type at all, and if I do forward declare, it fails at a later stage of compilation when it sees the actual generated enum. I don't really get to a state where I can static assert to begin with. – The-Big-K Nov 07 '18 at 02:18

0 Answers0