2

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?
DonBaka
  • 325
  • 2
  • 14
  • 3
    Doc should help [std::experimental::optional](https://en.cppreference.com/w/cpp/experimental/optional)/[std::optional](https://en.cppreference.com/w/cpp/utility/optional) (C++17). – Jarod42 Nov 29 '21 at 10:31

1 Answers1

9

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();
    }
    
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • [feel free to skip]A bit of follow up, even if the function parameter is optional, it always need a value for function call? – DonBaka Nov 29 '21 at 10:38
  • 1
    @DonBaka the parameter is not optional. It is a parameter of the type `std::[experimental::]optional`, and an object of that type can have the state of holding an object or not holding an object. `std::optional` is a type like `std::vector`, `std::string`, … – t.niese Nov 29 '21 at 10:40
  • 1
    Being the first argument to your function, you might want to consider the importance of this "optional" parameter in relation to the other parameters. Usually, "opt-in" arguments are better as the trailing parameters and use either default values or function overloading. – paddy Nov 29 '21 at 10:42