简体   繁体   中英

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?

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

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

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