简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM