How to access the value of a field in protobuf using field number in c++

329 Views Asked by At

let's say there is a situation like this,

message A {
...
}



message C {
 optional A a_in_c = 1;
}

message D {
 optional A a_in_d = 1;
}

Need to write a template function,
template<typename T>
void foo (T t) {
  // here T can be C or D. and need to access first field.
  // A a = first field of t.
  
}

how to do this? I know how to get the field descriptor using number but not able to get the value of it.

1

There are 1 best solutions below

0
On

So, in terms of structures, the following will work:

#include <iostream>
#include <string>

struct A {
    int x;
    double y;
};

struct C {
 A a_in_c{1};
};

struct D {
 A a_in_d{2};
};


template<typename T>
void foo (T t) {
  auto a = reinterpret_cast<A*>(&t);
  std::cout << a->x << "!\n";
}

int main()
{
  std::string name;
  D d;
  foo(d);
}

Keep in mind, however, that as long as serialization and de-serialization is done on one machine, it should work okay, but it gets tricky once you communicate between machines (endianess have to be taken into account, or more generally speaking memory layout). Additionally, following code will work only if A is the first field within C or D structure.

From design perspective, it's wiser to name the fields the same, because you are kinda killing the purpose of templates and duck-typing consuming T t like this.