So verwenden Sie boost :: optional

Ich versuche, mit boost::optional als unten.

#include <iostream>
#include <string>

#include <boost/optional.hpp>

struct myClass
{
   int myInt;
   void setInt(int input) { myInt = input; }
   int  getInt(){return myInt; }
};

boost::optional<myClass> func(const std::string &str)
{
   boost::optional<myClass> value;
   if(str.length() > 5)
   {
      //If greater than 5 length string. Set value to 10
      value.get().setInt(10);
   }
   else if (str.length() < 5)
   {
      //Else set it to 0
      value.get().setInt(0);
   }
   else
   {
      //If it is 5 set the value to 5
      value.get().setInt(5);
   }

   return value;
}


int main()
{
   boost::optional<myClass> v1 = func("3124");
   boost::optional<myClass> v2 = func("helloWorld");
   boost::optional<myClass> v3 = func("hello");

   if (v1)
       std::cout << "v1 is valid" << std::endl;
   else
       std::cout << "v1 is not valid" << std::endl;

   if (v2)
       std::cout << "v2 is valid" << std::endl;
   else
      std::cout << "v3 is not valid" << std::endl;

   if (v3)
      std::cout << "v3 is valid" << std::endl;
   else
      std::cout << "v3 is not valid" << std::endl;

  return 0;
 }

Bekomme ich folgenden Fehler

prog.exe:
/usr/local/boost-1.55.0/include/boost/optional/optional.hpp:631:
boost::optional::reference_type boost::optional::get() [mit T =
myClass; boost::optional::reference_type = myClass&]: Assertion
`this->is_initialized()' ist fehlgeschlagen.

Vermutlich die optionale variable nicht richtig initialisiert. Wie zu tun es der richtige Weg?

EDIT:: hat einige sehr gute Antworten, nur ein paar mehr Fragen 1. Ist es eine gute Idee zu verwenden make_optional am Ende 'func' Funktion und zurückgeben? Auch 2. Ich dachte, die Zuordnung boost::none ausdrücklich betonen, dass ich keinen Wert zuweisen und das ist, warum boost::none. Aber nicht sicher, ob das gültig ist?

InformationsquelleAutor der Frage polapts | 2014-03-06

Schreibe einen Kommentar