Boost :: optional doesn't let me reassign const value types

It seems to me that there should be four options boost::optional

  • optional<Foo> => contains mutable Foo and can be reassigned after initialization

  • optional<Foo const> const => contains the constant Foo and cannot be reassigned after initialization

  • optional<Foo> const => (should it?) contain mutable Foo, but cannot be reassigned after initialization

  • optional<Foo const> => (should?) hold const Foo and can be reassigned after initialization

The first 2 cases work as expected. But dereferencing is optional<Foo> constfor const Foo and optional<Foo const>does not allow reassigning after initialization (as discussed in this question ).

Remapping const value types is what I came across and the error:

/usr/include/boost/optional/optional.hpp:486: error: passing 'const Foo as' to this argument' Foo & Foo :: operator = (const Foo &) discards qualifiers [-fpermissive]

And this happens here:

void assign_value(argument_type val,is_not_reference_tag) { get_impl() = val; }

After construction, the implementation uses an assignment operator for the type with which you parameterized an optional parameter. Obviously, he does not want the left operand to be a const value. But why don't you let reset unconstant the optional parameter for the new const value, for example, in this case:

optional<Foo const> theFoo (maybeGetFoo());
while (someCondition) {

    // do some work involving calling some methods on theFoo
    // ...but they should only be const ones

    theFoo = maybeGetFoo();
}

Some questions:

  • Do I want it to be conceptually perfect, and the inability to do this is just an accident in implementation?

  • If I do not edit the sources of boost, then what is the clean way to implement the logic, as in the loop above, without utilizing boost :: optional at all?

  • , boost:: optional source ( , , , ), - ?

+5
3

(1) , "", , " " " ", ". , " " . .

(2) Foo, , , . , , .

optional<Foo> theMutableFoo (maybeGetFoo());
while (someCondition) {
    optional<Foo const> theFoo (theMutableFoo);

    // do some work involving calling some methods on theFoo
    // ...but they should only be const ones
    // ...therefore, just don't use theMutableFoo in here!

    theMutableFoo = maybeGetFoo();
}

, " " , , , . .

(3) , , @Andrzej. , , , ( ). , .


: @R.MartinhoFernandez, @KerrekSB

+1

​​ optional& optional<T (not a ref)>::operator= ( T const& rhs ):

: * , T, -.

, boost::optional<const Foo> theFoo;. boost::optional<> , :

theFoo=defaultFoo;

" defaultFoo theFoo ". , , const Foo. theFoo .

theFoo ,

theFoo=defaultFoo;

" defaultFoo theFoo ". theFoo ( const), ( ?).

, , , . , .


, boost::optional<...> :

* , . T copy-constructor.

, T, , , *theFoo = rhs.

+3

:

  • , T; .
  • . - optional_base. optional_base. optional_base , , . , reset (T), _, ().
  • reset (T) . .

.

+2

All Articles