Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
    }
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading