mardi 24 avril 2018

Cryptical cannot bind non-const lvalue reference to an rvalue message claiming two identical object types are different

i've been stuck on this for an hour now, and the programming book i have does exactly the same but without templates when i try to do this:

FancySafeArray<int> fsa(4);
    FancySafeArray<int> fsb(4);
    for(int i = 0; i < 4; i++) {
        fsa[i] = i;
        fsb[i] = i + 5;
    }
FancySafeArray<int> fsc = fsa + fsb;

I get the message:

main.cpp:52: error: cannot bind non-const lvalue reference of type ‘FancySafeArray<int>&’ to an rvalue of type ‘const FancySafeArray<int>’
     FancySafeArray<int> fsc = fsa + fsb;
                               ~~~~^~~~~

Which confuses me, because fsa and fsb are identically created This is my operator overload function:

template<class T>
const FancySafeArray<T> operator +(const FancySafeArray<T> &lhs, const FancySafeArray<T> &rhs)
{
    int size = lhs.getSize() + rhs.getSize();
    FancySafeArray<T> tmp(size);
    for(int i = 0; i < lhs.getSize();  i++) {
        tmp[i] = lhs[i];
    }
    for(int i = 0; i < rhs.getSize();  i++) {
        tmp[i + lhs.getSize()] + rhs[i];
    }

    return tmp;
}

in my head this makes perfect sense, and it seems to match 1:1 with an example in my book. Googling the issue leads to people having other issues, like trying to get the reference of a temporary variable, so i am completely lost for solutions. What have i done wrong?

Aucun commentaire:

Enregistrer un commentaire