1

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, e.g. 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?

sgarizvi
  • 16,623
  • 9
  • 64
  • 98
anurudh
  • 338
  • 1
  • 4
  • 15
  • `I have to implement a data structure in c++` then why the `C` tag? – Sourav Ghosh Mar 11 '15 at 05:50
  • How about [Boost optional](http://www.boost.org/doc/libs/1_57_0/libs/optional/doc/html/index.html)? – Some programmer dude Mar 11 '15 at 05:53
  • Is it truly optional or do you actually have different structures. ie, should this not be using inheritance? – Leon Mar 11 '15 at 06:00
  • @Joaechim, yes i heard about the boost optional, but i guess for boost optional, i have to include boost library, which can't do in my project, my lib should be dependent only in std c++. – anurudh Mar 11 '15 at 06:04
  • Possible duplicate of [Best way to encapsulate "optional" fields within a struct generically in C++?](https://stackoverflow.com/questions/5379102/best-way-to-encapsulate-optional-fields-within-a-struct-generically-in-c) – Gabriel Devillers Oct 22 '18 at 07:11

1 Answers1

3

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.

Daniel Frey
  • 55,810
  • 13
  • 122
  • 180