c++templatespass-by-referencefunction-declarationpass-by-rvalue-reference

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


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?


Solution

  • 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 */
        };
    };