Skip to content

Allow initialization of optionals from convertible type U (or optional<U>) #16

@hostilefork

Description

@hostilefork

Currently it is possible to initialize one optional from another if their types match exactly. But one should ideally be able to initialize one optional from another if the types are convertible:

#include <memory>
#include "Optional/optional.hpp"

using std::experimental::optional;
using std::experimental::make_optional;
using std::shared_ptr;

int main() {
    shared_ptr<int> i (new int (1020));
    shared_ptr<int const> ic = i;

    optional<shared_ptr<int>> oi = i;
    optional<shared_ptr<int>> oi2 = oi;

    // Everything up to here works, but these fail...
    optional<shared_ptr<int const>> oic = i;
    optional<shared_ptr<int const>> oic2 = oi;
}

The error you get on oic is:

conversion from ‘std::shared_ptr<int>’ to non-scalar type ‘std::experimental::optional<std::shared_ptr<const int>>’ requested

...and on oic2 you get:

conversion from ‘std::experimental::optional<std::shared_ptr<int>>’ to non-scalar type ‘std::experimental::optional<std::shared_ptr<const int>>’ requested

Similar arguments apply for cases like:

class Foo {};
class Bar : public Foo {};

optional<unique_ptr<Foo>> makeOptionalFoo() {
    return unique_ptr<Bar>(new Bar);
}

Which doesn't currently work, but I think it should.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions