简体   繁体   中英

Optional Variable(variable structure) in structure in c++

I have to implement a data structure in c++, which have optional variable. As

 struct xyz
 {
      int x;  //required
      int y;  //optional
      bool a;  // required
      bool b;  // optional
      bool c;  // optional
      std::string d; //optional
      std::string e; // required
      ........

 }

Some of the variables are required means fixed, but some of the variable is optional.

I can't set any default value to the variables to tell its optional, eg bool variable has only two states and each state has a meaning for our project. And same for integer as well every value of integer is useful data for me.

I googled but not found any satisfactory answer.

I tried with std::vector but it not looks good.

 struct xyz
 {
      int x;  //required
      std::vector<int> y;  //optional
      bool a;  // required
      std::vector<bool> b;  // optional
      ........
 }

In this method we can check the size of vector, if zero means variable is not present else the variable has the desired value.

But for a bit bool or 4 byte int creating a std::vector is overhead to data structure.

Can any one suggest out of these methods?

Some compilers already ship with the upcoming std::optional - which is called std::experimental::optional for now. I am already using it for some time now (GCC 4.9+) and it's in good shape.

If your compiler does not have it yet but has good-enough support for C++11/C++14, you may also use a single header from Andrzej Krzemieński's reference implementation to avoid the dependency to Boost.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM