Home > Net >  How to replace #include <option>
How to replace #include <option>

Time:09-13

I come to you today with another question that my brain can't process by itself: I got a cpp file that includes optional as a header file. Unfortunately, this works only on c 17 forwards, and I'm trying to compile it in c 14. This cpp file uses optional like this

std::optional<std::string> GetStringPropertyValueFromJson(const std::string& Property, const web::json::value& Json)
{
    if (Json.has_field(utility::conversions::to_string_t(Property)))
    {
        auto& propertyValue = Json.at(utility::conversions::to_string_t(Property));
        if (propertyValue.is_string())
        {
            return std::optional<std::string>{utility::conversions::to_utf8string(propertyValue.as_string())};
        }
    }

    return std::nullopt;
}

and then the function is used to assign values like this:

std::string tokenType = GetStringPropertyValueFromJson("token_type", responseContent).value_or("");
std::string accessToken = GetStringPropertyValueFromJson("access_token", responseContent).value_or("");

Please help me with a proper substitution for OPTIONAL. Thanks and much love

PS: From what i've read, you can replace optional with pair somehow in order to get a similar result, but I don't really know how exactly.

PPS: I am new here so any tips on how to better write my questions or anything else are greatly appreciated :)

CodePudding user response:

I guess in C 14 the optional header could be included by #include <experimental/optional>.

CodePudding user response:

Change your method signature to

std::string GetStringPropertyValueFromJson(const std::string& Property, const web::json::value& Json)

and in the end just return the empty string

return "";

Then later in your code use it without std::optional::value_or:

std::string tokenType = GetStringPropertyValueFromJson("token_type", responseContent);

The logic is exactly the same and you don't use std::optional.

  •  Tags:  
  • c
  • Related