【问题标题】:How to access the value of a field in protobuf using field number in c++如何使用c ++中的字段编号访问protobuf中字段的值
【发布时间】:2021-01-03 01:13:21
【问题描述】:

假设有这样的情况,

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.
  
}

如何做到这一点?我知道如何使用数字获取字段描述符,但无法获取它的值。

【问题讨论】:

    标签: c++ protobuf-c


    【解决方案1】:

    因此,就结构而言,以下内容将起作用:

    #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);
    }
    

    但是请记住,只要在一台机器上完成序列化和反序列化,它应该可以正常工作,但是一旦在机器之间进行通信就会变得棘手(必须考虑字节序,或更一般地说口语记忆布局)。此外,仅当 ACD 结构中的第一个字段时,以下代码才有效。

    从设计的角度来看,将字段命名为相同的名称更明智,因为您有点扼杀模板的用途,并且像这样使用 T t 进行鸭式输入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多