rvalue variant with lvalue references does not compile

Open
#73 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
35/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
cpp
Domain
backend

Research direction

Start by reproducing the C++ example with boost::apply_visitor, comparing the working lvalue variant call with the failing temporary call. Trace the apply_visitor overloads involved in the rvalue case and verify that a variant containing lvalue references preserves those references; done means the failing call compiles and both referenced values are modified as asserted.

Written by the indexing model from the issue text.

Description

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.

Dominant language
C++
Stars
47
Forks
71
PR merge metrics
No merged PRs in 30d

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from boostorg/variant

All issues in boostorg/variant

Similar issues

More C++ issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.