Aviv Cohn
Aviv Cohn

Reputation: 17243

C++ Error: 'no matching function for call to [class]::[function]'

I have a template class template <typename T> class MyClass with a method:

void add (T& item) {
    data[indexToInsert++] = &item; // data is an array of T*
}

In main:

MyClass<int> thing;
thing.add(10);

On the second line, I get this error:

no matching function for call to MyClass::add(int)

Why is this happening?

Upvotes: 2

Views: 1200

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

Your member function expects a reference to T, which would be int&. You are passing a plain int, not a variable of type int, of which C++ could take a reference. This is not allowed: you can pass an int in place of a constant reference, but not in place of a non-constant reference.

The reason for this is that when you pass a value in place of a constant reference, C++ can create a temporary object, copy the value into it, and pass a reference to that temporary to a function. Doing the same for a non-constant reference would be incorrect, because your code has no access to a potentially modifiable temporary object.

Your code illustrates the reason why this would be incorrect: you pass 10 to your function, but the function takes the address of the item. What is the address of 10? C++ does not know, because integer literal 10 does not have an address.

You can fix the call by providing a variable of type int, setting it to 10, and calling add:

MyClass<int> thing;
int ten = 10;
thing.add(ten);

However, you need to make sure that thing would not have a wider scope than ten, because otherwise you would end up with a "dangling pointer" inside the data array of the thing object.

Upvotes: 5

Related Questions