protobuf には、継承を実装するためのいくつかのオプションがあります。「ネストされた拡張機能」はその1つです: http://www.indelible.org/ink/protobuf-polymorphism/
ここで興味深いのは、シリアル化されたファイルを読み取る方法です。動物を正しい Dog または Cat にキャストするには、Animal.type を拡張識別子に対応させる Map を作成する必要があります。ただし、上記の Web サイトで提供されている例では、使用されている言語は Python です。これは、キーのタイプまたは値のタイプを指定せずに Map を初期化できることを意味します。そしてそれはうまくいきます:
# Unpack the serialized bytes.
animal = Animal()
animal.ParseFromString(bytes)
# Determine the appropriate extension type to use.
extension_map = { Animal.Cat: Cat.animal, Animal.Dog: Dog.animal }
extension = animal.Extensions[extension_map[animal.type]]
ただし、このようなマップを C++ で実装するには、キーの型と値の型が必須です。では、2 つの異なる拡張 ID を同じマップに格納できるようにするには、値にどの型を使用すればよいでしょうか?
Map<Animal::Type, ::google::protobuf::internal::ExtensionIdentifier>
?
残念ながら、これは明らかに機能しません。
また、ここに書き込みパラダイムをコピーして貼り付けます: from animals_pb2 import *
# Construct the polymorphic base message type.
animal = Animal()
animal.type = Animal.Cat
# Create the subclass type by referencing the appropriate extension type.
# Note that this uses the self-referential field (Cat.animal) from within
# nested message extension.
cat = animal.Extensions[Cat.animal]
cat.declawed = True
# Serialize the complete message contents to a string. It will end up
# looking roughly like this: [ type [ declawed ] ]
bytes = animal.SerializeToString()
Extensions() 関数を使用すると、拡張機能の識別子を使用して拡張機能を取得できます。