封装“可选"的最佳方式结构中的字段通常在 C++ 中? [英] Best way to encapsulate "optional" fields within a struct generically in C++?

查看:36
本文介绍了封装“可选"的最佳方式结构中的字段通常在 C++ 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多具体结构,我想将字段指定为可选(存在或不存在).只是想知道人们对实现这一目标有什么想法.这是一个示例结构(字段也可以是其他结构,甚至是结构的向量):

I have many concrete-structs and I want to designate fields as optional (present or not-present). Just wondering what ideas people have for achieving this. Here is an example struct (fields can be other structs as well, even vectors of structs):

 struct LogonMessage_t
       {
          Header_t header; // this points to another struct containing all primitives
          std::string username;
          std::string password;
          std::vector<LogonOption_t> LogonOptions;
          int subaccountid;
          std::string Text;
       }

我想将所有字段默认为不存在并一一启用它们,也许在它们的设置器中.由于生成了这些结构,因此最好使用通用方法.

I'd like to default all fields to not-present and enable them one by one, perhaps in their setters. Since these structs are generated, a generic method would be preferable.

到目前为止,我的想法是:

My ideas so far are:

  1. 字段位图,指示是否设置了字段
  2. 使用标记值(\0"代表 std::string,-1 代表 int,-1.0f 代表浮点
  3. 某种模板容器/代理封装了每个字段以指示它是否已设置,有什么想法吗?我认为这可能是最好的方法.

顺便说一句,使用映射或其他 STL 容器来封装字段在这里不起作用,它们需要是具体的结构.

Btw, using maps or other STL containers to encapsulate the fields won't work here, they need to be concrete structs.

推荐答案

听起来你想要boost.可选.

这篇关于封装“可选"的最佳方式结构中的字段通常在 C++ 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆