c++ - 从成员变量或成员函数中读取值的 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 一起使用。
解决方案
You can use std::invoke()
for this problem.
推荐阅读
- vbscript - 替换multiplis文件txt中的字符
- java - 如何使用 javapoet 动态生成代码?更改方法参数
- objective-c-blocks - 如何正确构造对 requestAuthorizationOfType: 的方法调用,NSWorkspace 方法?
- java - 如何使用 Mockito 将 void 方法测试到服务类中?
- sql - 使临时表永久化
- c++ - 从内存导入密钥时出现 Crypto++ BERDecode 异常?
- python - DSaaS 使用 Python 添加全局规则
- python - 在小提琴图中可视化线图
- java - 如何将 MockWebServer 中的响应分配给预期的请求?
- python - 如何监督变分自动编码器 (VAE) 中的潜在变量