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:
- Is there a way to handle this case?
- 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?
CodePudding user response:
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(); }