5

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
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
JeyJ
  • 3,582
  • 4
  • 35
  • 83

1 Answers1

9

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;
    }
    
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • or argument type as *rvalue* : `void operator() (G&& a)` – JeJo Jun 16 '18 at 05:21
  • @JeJo, or that. Thanks for the suggestion. – R Sahu Jun 16 '18 at 05:39
  • So in c++ when I'm passing an lvalue I cant pass the variable by reference ? Why then setting the parameter`s type to G&& also solves the problem? – JeyJ Jun 16 '18 at 07:08
  • Moreover the solution G &a const raised the same error. – JeyJ Jun 16 '18 at 07:21
  • @JeyJ `s(5)` passes rvalue. And it cannot be bound to non-const reference (https://stackoverflow.com/questions/13826897/why-not-non-const-reference-to-temporary-objects?noredirect=1&lq=1 ). `s(const G&)` works because its const and `s(G&&)` works, because it's not rvalue reference but a universal reference (https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers) with special rules. – Quimby Jun 16 '18 at 10:59