Boost logo

Boost :

From: anshu khare (anshukhare1998_at_[hidden])
Date: 2020-01-19 12:02:39


However when I run

boost::optional<int> i= 5;
cout << get_optional_value_or(i, 7) ;

I get the output as 5.

And when I run

boost::optional<int> i= {};
cout << get_optional_value_or(i, 7) ;

I get the output as 7.

On Sun, 19 Jan, 2020, 5:29 PM anshu khare, <anshukhare1998_at_[hidden]> wrote:

> When I run the following code :
>
>
> int i = {};
> boost::optional<int> v = i;
> cout << get_optional_value_or(v, 1)
>
> I get a compilation error in the third line.
>
>
>
>
>
> On Sun, 19 Jan, 2020, 5:12 PM Mateusz Loskot via Boost, <
> boost_at_[hidden]> wrote:
>
>> On Sun, 19 Jan 2020 at 11:57, anshu khare via Boost
>> <boost_at_[hidden]> wrote:
>> > But when I run
>> >
>> > const std::string i = {};
>> > boost::optional<const std::string&> str = i;
>> > cout << get_optional_value_or(str, "some other string") ;
>> >
>> > The output is an empty string.
>> > Shouldn't it give "some other string as output"
>>
>> No, it should not.
>>
>> From the documentation:
>> "Class template optional is a wrapper for representing 'optional' (or
>> 'nullable')
>> objects who may not (yet) contain a valid value."
>>
>> An empty string in `i` variable IS a valid value, so `str` is set with
>> a valid value,
>> Since it is valid value, get_optional_value_or returns that valid value
>> and not the "some other string".
>>
>> > because if I run the same
>> > code with integer it gives the second parameter of
>> get_optional_value_or()
>> > as output?
>>
>> Are you sure?
>>
>> This is expected to print 0, the valid value of `i` and not the default 1:
>>
>> int i = {};
>> boost::optional<int> v = i;
>> cout << get_optional_value_or(v, 1);
>>
>> Best regards,
>> --
>> Mateusz Loskot, http://mateusz.loskot.net
>>
>> _______________________________________________
>> Unsubscribe & other changes:
>> http://lists.boost.org/mailman/listinfo.cgi/boost
>>
>


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk