简体   繁体   English

C++ 模板类:错误:没有用于调用的匹配函数

[英]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.创建一个值为 5 的int类型临时对象作为函数的参数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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