Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot convert argument 1 from 'int' to 'int &'

Tags:

c++

I'm getting the next error and I cannot find the reason for it:

Error C2664 'void SumID<long>::operator ()<int>(G &)': cannot convert argument 1 from 'int' to 'int &'

Why is passing an int by reference problematic?

I have the next class:

template <class T>
class SumID {
private:
    T sumid;

public:
    SumID():sumid()
    {
    }

    SumID(T s)
    {
        sumid = s;
    }

    T getSumID()
    {
        cout << "inside getSum";
        return sumid;
    }

    template <class G>
    void operator() (G& a)
    {
        sumid = sumid+ a;
    }
};

my main :

SumID<long> s;
for (int i = 0; i < 5; i++)
    s(5); // <-- error here
like image 394
JeyJ Avatar asked Jan 03 '23 06:01

JeyJ


1 Answers

When use s(5); the argument, 5, is not an lvalue. Hence, it cannot be used when the argument type is G&.

You can resolve the problem using one or both of the following approaches.

  1. Create a variable and use it in the call.

    int x = 5;
    s(x);
    
  2. Change the argument type to just G, G&& or G const&.

    template <class G>
    void operator() (G a)  // Or (G&& a) or (G const& a)
    {
       sumid = sumid+ a;
    }
    
like image 67
R Sahu Avatar answered Jan 12 '23 19:01

R Sahu