Search code examples
c++tuplesconstantsreturn-value

C++ - How do I return 2 values using tuple and auto[value1, value2] as c++ says value1 should be const?


I'm coding a Polynom class in c++. In the following link, it is explained how to return several values using tuple : Returning multiple values from a C++ function

So I tried to code as indicated to return the quotient and the remainder of the polynomial division but it does not work.

Here is my division method :

tuple<Polynome, Polynome> division(Polynome& D)
{   
    Polynome Q;
    Polynome R(*this);
    Polynome nul;
    int delta(degre() - D.degre());
    float a;

    while (delta >= 0 && R != nul)
    {
        a = R.top() / D.top();
        Polynome nouveauPoly(a, delta);
        Q = Q + nouveauPoly;
        R = R - nouveauPoly * D;
        delta = R.degre() - D.degre();
    }
    return {Q, R};
}

Then, when I do as indicated in the link above and begin to code my own operator :

Polynome operator/(Polynome& D)
{
    auto [Q, R] = division(D);
}

I get an error telling me Q should be constant value. I don't understand why Q should be so, and where the error come from, especially regarding that this code comes from a top answer in stackoverflow. I tried to first declare the polynomes Q and R but it did not change anything.

Ultimately I found a way to achieve what I wanted using tuples, but I'm still wanting to know exactly why the indicated answer did not work for me.

Thank you very much


Solution

  • It might be that Structured Binding does not work with your compiler version (or the C++ version option). That requires C++17.

    If you can't go for C++17, you might want to try out older ways to do this:

    Instead of

    auto [Q, R] = division(D);
    

    use

    Polynome Q, R;
    std::tie(Q, R) = division(D);
    

    (This requires #include <tuple>, but I assume that is included already anyway.)