Search code examples
c++stringstdoptional

How to set a string to an optional string value?


Due to some constraint in the program(C++), I have a case where I am assigning an optional string to a string variable, which give the following error: error: no match for ‘operator=’ ...

The piece of code is something like:

void blah(std::experimental::optional<std::string> foo, // more parameters)
{
    std::string bar;
    if(foo)
    {
        bar = foo; //error
    }

    // more code
}

Attempts:

I tried to convert the types to match by using:

bar = static_cast<std::string>(foo);

which ended up showing this error:

error: no matching function for call to ‘std::basic_string<char>::basic_string(std::experimental::optional<std::basic_string<char> >&)’

I am wondering:

  1. Is there a way to handle this case?
  2. Or else it is a design limitation and I have to use some other approach instead of assigning a optional string to a normal string?

Solution

  • You have several ways:

    • /*const*/std::string bar = foo.value_or("some default value");
      
    • std::string bar;
      if (foo) {
          bar = *foo;
      }
      
    • std::string bar;
      if (foo) {
          bar = foo.value();
      }