Skip to content

rvalue variant with lvalue references does not compile #73

@slymz

Description

@slymz

As far as I can tell, the following is a legitimate code which attempts to a temporary variant to keep references. But it fails to compile:

struct Changer : boost::static_visitor<void> {
    void operator()(int& i) const  {
        i += 10;
    }
    void operator()(double& d) const {
        d += 20;
    }
};

auto getVar(int choose, int& i, double& d){
    using V = boost::variant<int&, double&>;
    return choose == 0 ? V(i) : V(d);
}

void foo() {
    int i = 0;
    double d = 0;
    Changer c;
    auto v1 = getVar(0,i,d);
    boost::apply_visitor(c, v1); // OK
    assert(i == 10);
    assert(d == 0.);
    boost::apply_visitor(c, getVar(1,i,d));  // ERROR
    assert(i == 10);
    assert(d == 20.);
}
error: no matching function for call to object of type 'Changer'

See https://godbolt.org/z/FVVA_t for the error.

It seems apply_visitor is making the assumption that if a variant is rvalue, so should be the elements. But (unlike std::variant) boost::variant supports references as elements, so the two are decoupled.

This makes variants impossible to use as proxy objects.

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