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
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.
Create a variable and use it in the call.
int x = 5;
s(x);
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With