首页 > 解决方案 > 从成员变量或成员函数中读取值的 C++ 模板

问题描述

我正在编写代码生成器并使用平面缓冲区来生成类。代码生成器的其余部分将在 C++ 中使用这些类。

我无法弄清楚如何保持 API 一致以读取 flatbuffer 可能生成的两种不同类型的类的数据。我在示例中使用对象 api (testRecordT) 来处理需要写入(并且也可以读回)对象的情况,并在只能读取数据时使用 flatbuffer 覆盖。

我无法获得任何模板或免费函数来为我提供在这两种情况下都可以使用的一致 api。

下面是我想要开始工作的一个片段。

struct testRecordT {
  int32_t field1;
  std::string field2;
};

struct testRecord {
    int32_t field1() const {
        return 0;
        // flatbuffer generated - return GetField<int32_t>(VT_FIELD1, 0);
    }
    const flatbuffers::String *field2() const {
        return nullptr;
       // flatbuffer generated - return GetPointer<const flatbuffers::String *>(VT_FIELD3);
    }

};

void Test() {
   testRecordT * members; // assume pointers are valid
   testRecord * memberFunctions;

// Need to be able to create a read function/template that would work. This would simplify the code generation a lot. I can generate either one below, as long as it is consistent in both cases.
   auto r = read(members->field1); // or read(members,field1)
   auto v = read(memberFunctions->field1); // or read(memberFunctions,field1)
}

读取函数或模板函数应该是一致的。任何指示或想法都会有所帮助。我将 C++17 与 gcc 7.3.1 一起使用。

标签: c++templatesc++17flatbuffers

解决方案


You can use std::invoke() for this problem.


推荐阅读