在C++中一般封装结构中的"可选"字段的最佳方法是什么?

chr*_*irk 5 c++ templates struct optional-variables

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

 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;
       }
Run Code Online (Sandbox Code Playgroud)

我想将所有字段默认为不存在并逐个启用它们,也许是在它们的setter中.由于生成了这些结构,因此优选通用方法.

我到目前为止的想法是:

  1. 指示字段是否已设置的字段位图
  2. 使用sentinel值(对于std :: string为"\ 0",对于int为-1​​,对于float为-1.0f)
  3. 某种模板容器/代理封装每个字段以指示它是否已设置,任何想法?我认为这可能是最好的方法.

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

ild*_*arn 6

听起来你想要提升.可选的.