Skip to content

implicit conversion from boost::optional<T> to boost::optional<const T&> #142

@dmenendez-gruposantander

Description

I am using boost::optional<const T&> to pass parameters by "optional const-reference", to replace some uses of raw pointers.

Old code:

void f(const A* a) {
    if (a) ... // do something with *a
    else ... // do something else without *a
}

// client code
void g1(const A& a) { f( &a ); }
void g2() { f( nullptr ); }
void g3(boost::optional<A> a) { f( a.get_ptr() ); }

New code:

void f(boost::optional<const A&> a) {
    if (a) ... // do something with *a
    else ... // do something else without *a
}

// client code
void g1(const A& a) { f( a ); }
void g2() { f( boost::none ); }
void g3(boost::optional<A> a) { f(  ???  ); }

The simplest way I see right now is to make the conversion explicitly at each call site using boost::optional::map()

a.map( [](const A& x) -> const A& {return x;} )

which I consider a bit redundant.

AFAIU there is no implicit conversion from boost::optional<T> to boost::optional<const T&>, but there could be, to make these use cases easier.

What do you think about this feature request?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions