C++ Template class: error: no matching function for call to

1.6k Views Asked by At

I have the following template class:

template <typename T> class ResourcePool {
    inline void return_resource(T& instance) {
        /* do something */
    };
};

Then, in my main function, I do:

ResoucePool<int> pool;
pool.return_resource(5);

And I get the following error:

error: no matching function for call to `ResourcePool<int>::return_resource(int)`

Any idea what I'm doing wrong?

2

There are 2 best solutions below

0
On BEST ANSWER

In this call

pool.return_resource(5);

a temporary object of type int with the value 5 is created as the function's argument.

A temporary object can not be bind with a non-constant reference.

Declare the function like

template <typename T> class ResourcePool {
    inline void return_resource( const T& instance) {
        /* do something */
    };
};
0
On

You are passing a temporary to a function that expect a reference. This bind can not be done. Try:

template <typename T> class ResourcePool {
    inline void return_resource(const T& instance) { // <---
    /* do something */
    };
};

or

template <typename T> class ResourcePool {
    inline void return_resource(T instance) {  // <----
    /* do something */
    };
};